package com.beaut.project.service;

import com.beaut.project.dao.*;
import com.beaut.project.util.StaticData;
import com.beaut.project.util.Utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@Transactional(rollbackFor = Exception.class)
@Service("workFlowService")
public class WorkFlowService {
	@Autowired
	FlowMapper workFlowMapper;
	@Autowired
	XMMapper xMMapper;
	@Autowired
	XMAssistMapper xMAssistMapper;//项目辅助管理
	@Autowired
	private CRMMapper crmMapper;
	@Autowired
	private GDMapper gdMapper;
	@Autowired
	private WareHouseMapper wareHouseMapper;
	@Autowired
	private XMAssistService xmAssistService;

	@Autowired
	private FinanceMapper financeMapper;	//财务模块

	@Autowired
	private XMFinanceMapper xmFinanceMapper;	//项目业务收支部分
	
	public String toViewBusiness(Map<String,Object> map){
    	Map m=workFlowMapper.getDataFormId(map);
    String formId=m.get("FORM_SEQ_ID").toString();
    String flowId=map.get("flowId").toString();
    String tableName="form_data_"+flowId+"_"+formId;
    map.put("tableName", tableName);
    Map m1=workFlowMapper.getViewBusinessUrl(map);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", Utility.toJson(m1));
	}
	/**
	 * 库存盘点审批
	 * @param map
	 * @return
	 */
	public String backToGDUpdateInventory(Map<String,Object> map){
		map.put("inventory_id", map.get("key"));
		Map<String,Object>mapInv=wareHouseMapper.getInventoryById(map);//得到经办人和盘点备注
		List<Map<String,Object>>listPro=wareHouseMapper.listInventoryDetail(map);
    	String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
    	List<Map<String,Object>> dbList=new ArrayList<Map<String,Object>>();
    	for(int i=0;i<listPro.size();i++){
    		Map<String,Object> m= new HashMap<String,Object>();
    		 BigInteger b = new BigInteger(String.valueOf(listPro.get(i).get("different_num")));
             b = b.abs();
    		m.put("warehouse_id", listPro.get(i).get("warehouse_id"));
    		m.put("gd_id", "");
    		m.put("product_id", listPro.get(i).get("material_id"));
    		m.put("cost", 0);//不计价格
    		m.put("num",  b);
    		m.put("person_id", mapInv.get("person_id"));
    		m.put("person", mapInv.get("person"));
    		m.put("operation_date", operation_date);
    		m.put("business_id", map.get("key"));
    		//厂家库
			if("4".equals(String.valueOf( listPro.get(i).get("type")))){
				m.put("project_id", "");
				m.put("supplier_id", listPro.get(i).get("business_id"));
				m.put("customer_id", "");
			}
			//客户库
			if("0".equals(String.valueOf( listPro.get(i).get("type")))){			
				m.put("project_id", "");
				m.put("customer_id", listPro.get(i).get("business_id"));
				m.put("supplier_id", "");
			}
			//工余料库
			if("2".equals(String.valueOf( listPro.get(i).get("type")))){			
				m.put("project_id","");
				m.put("customer_id", "");
				m.put("supplier_id", "");
			}
			
    		Map<String,Object>mapDb=wareHouseMapper.getMaterialDbById(m);//得到db_id
    		mapDb.put("num", b);
    		mapDb.put("db_id", mapDb.get("id"));
    		if(Integer.parseInt(String.valueOf(listPro.get(i).get("different_num")))>0){
				//如果产品所在库已经存在，那么不继续添加新产品而是直接增加数量
    			m.put("business_type", StaticData.CP_INVENTORY_OUT);
    			m.put("summary", "盘点出库【"+mapInv.get("code")+"】库存减少");
    			m.put("direction", StaticData.DB_OUT);
    			wareHouseMapper.subtractDBNum(mapDb);
			}else{
				m.put("business_type", StaticData.CP_INVENTORY_IN);
				m.put("summary", "盘点入库【"+mapInv.get("code")+"】库存增加");
				m.put("direction", StaticData.DB_IN);
				wareHouseMapper.addDBNum(mapDb);
			}
    		dbList.add(m);
    	}
    	wareHouseMapper.addDBLog(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	/**
	 * 产品入库审批
	 * @param map
	 * @return
	 */
	public String backToGDUpdateGDProductStatus(Map<String,Object> map){
		map.put("c_s_id", map.get("key"));
		Map<String,Object>mapCM=wareHouseMapper.getCustomerMaterialById(map);
		String warehouse_id = String.valueOf(mapCM.get("warehouse_id"));
		String customer_id = String.valueOf(mapCM.get("customer_id"));
		String supplier_id = String.valueOf(mapCM.get("supplier_id"));
		List<Map<String,Object>>listPro=wareHouseMapper.getCSMaterialByCsId(map);
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		List<Map<String,Object>> dbList=new ArrayList<Map<String,Object>>();
		for(int i=0;i<listPro.size();i++){
			Map<String,Object> m= new HashMap<String,Object>();
			m.put("warehouse_id", warehouse_id);
			m.put("project_id", "");
			m.put("gd_id", "");
			m.put("product_id", listPro.get(i).get("product_id"));
			m.put("cost", 0);//不计价格
			m.put("num", listPro.get(i).get("num"));
			m.put("top", listPro.get(i).get("top"));
			m.put("low", listPro.get(i).get("low"));
			m.put("person_id", mapCM.get("person_id"));
			m.put("person", mapCM.get("person_name"));
			m.put("operation_date", operation_date);
			m.put("direction", StaticData.DB_IN);
			m.put("business_id", map.get("key"));
			mapCM.put("product_id", listPro.get(i).get("product_id"));
			String obj=null;
			if((!"null".equals(customer_id)||!"".equals(customer_id))&&("null".equals(supplier_id)||"".equals(supplier_id))){
				m.put("business_type", StaticData.CP_CUST_IN);
				m.put("customer_id", customer_id);
				m.put("supplier_id", obj);
				m.put("summary", "客户库入库【"+getCustomerName(customer_id)+"】");
				
			}else{
				m.put("business_type", StaticData.CP_SUPPLIER_IN);
				m.put("customer_id", obj);
				m.put("supplier_id", supplier_id);
				m.put("summary", "厂家库入库【"+getSupplierName(supplier_id)+"】");
				
				
			}
			mapCM.put("product_id", listPro.get(i).get("product_id"));
			Map<String,Object>mapMartial=wareHouseMapper.getMaterialDbById(mapCM);
			if(mapMartial==null||mapMartial.isEmpty()){
				//如果产品所在库已经存在，那么不继续添加新产品而是直接增加数量
				wareHouseMapper.addCustomerOrSupplierMaterialDB(m);
			}else{
				wareHouseMapper.updateCustomerOrSupplierMaterialDB(m);
			}
			dbList.add(m);
		}
		wareHouseMapper.addDBLog(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	/**
	 * 工单预算调整回调函数
	 * @param map
	 * @return
	 */
	public String backToGDChangeAssume(Map<String,Object> map){
		String change_id = String.valueOf(map.get("key"));
		map.put("change_id", change_id);
		Map<String,Object> baseMap = gdMapper.getGDChangeAssumeById(map);
		String control = String.valueOf(baseMap.get("after_control"));
		String gd_id = String.valueOf(baseMap.get("gd_id"));
		map.put("gd_id", gd_id);
		
		List<Map<String,String>> detailList = new ArrayList<Map<String,String>>();
		List<Map<String,Object>> fbList = gdMapper.getChangeAssumeFB(map);
		gdMapper.deleteGDFBDetail(map);
		for(int i=0;i<fbList.size();i++){
			Map<String,Object> m = fbList.get(i);
			Map<String,String> rtMap = new HashMap<String,String>();
			rtMap.put("gd_id", gd_id);
			rtMap.put("fb_item_id", String.valueOf(m.get("fb_item_id")));
			rtMap.put("fb_item_name", String.valueOf(m.get("fb_item_name")));
			rtMap.put("budget", String.valueOf(m.get("after_budget")));
			rtMap.put("budget_remark", String.valueOf(m.get("after_budget_remark")));
			detailList.add(rtMap);
		}
    	gdMapper.addGDFBDetail(detailList);
    	
		List<Map<String,Object>> mList = gdMapper.getChangeAssumeMaterial(map);
		List<Map<String,String>> materialList = new ArrayList<Map<String,String>>();
		gdMapper.deleteGDMaterial(map);
		for(int i=0;i<mList.size();i++){
			Map<String,Object> m = mList.get(i);
			Map<String,String> rtMap = new HashMap<String,String>();
			rtMap.put("gd_id", gd_id);
			rtMap.put("material_id", String.valueOf(m.get("material_id")));
			rtMap.put("num", String.valueOf(m.get("after_num")));
			rtMap.put("control", control);
			rtMap.put("remark", String.valueOf(m.get("after_remark")));
			materialList.add(rtMap);
		}
		gdMapper.addGDMaterial(materialList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	public String backToGDUpdateXmCheckStatus(Map<String,Object> map){
		String check_id = String.valueOf(map.get("key"));
		map.put("id", check_id);
		Map<String, Object> checkMap = xMMapper.getXmCheckById(map);
		//项目辅助状态处理
		Map<String,Object> m=new HashMap<String, Object>();
		m.put("xm_id", checkMap.get("xm_id"));
		m.put("xm_business_step", StaticData.XM_HAS_YS);
		xMAssistMapper.addXMBusinessStep(m);
		//查询出是否有需要付款采购信息
//		int sCount = workFlowMapper.getSupplierCount(m);
		m.put("type", 0);
		int balance = workFlowMapper.hasBalance(m);//甲供
		m.put("type",1);
		int balance1 = workFlowMapper.hasBalance(m);//乙供
			Map<String,Object> mapNo=new HashMap<String,Object>();
			mapNo.put("xm_id", checkMap.get("xm_id"));
			if(balance == 0 && balance1 == 0){
				mapNo.put("no_material","1");//无材料
				checkMap.put("xm_progress_status", "5");
				workFlowMapper.backToGDUpdateXmCheckStatus(checkMap);
			}else{
				mapNo.put("no_material","0");//有材料
				checkMap.put("xm_progress_status", "4");
				workFlowMapper.backToGDUpdateXmCheckStatus(checkMap);
			}
//			}else if(balance>0&&sCount==0){
//				mapNo.put("no_material","2");//有材料甲供材
//			}else if(balance1>0&&sCount>0){
//				mapNo.put("no_material","0");//有材料
//			}
			xMAssistMapper.updateXMNoMaterial(mapNo);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	public String backToGDUpdateContract(Map<String,Object> map){
		String contract_id = String.valueOf(map.get("key"));
		map.put("id", contract_id);
		Map<String, Object> contractMap = xMMapper.getXmContractById(map);
		workFlowMapper.backToGDUpdateXmBaseContract(contractMap);
		return Utility.rtJson(Utility.RETURN_OK, "更新成功", null);
	}
	public String backToGDUpdateNoContract(Map<String,Object> map){
		String id = String.valueOf(map.get("key"));
		map.put("id", id);
		map.put("contract_type", 1);
		workFlowMapper.backToGDUpdateXmBaseContract(map);
		return Utility.rtJson(Utility.RETURN_OK, "更新成功", null);
	}
	public String backToGDPurchaseApply(Map<String,Object> map){
		String apply_id = String.valueOf(map.get("key"));
		map.put("apply_id", apply_id);
		Map<String, Object> purchaseApplyMap = gdMapper.getPurchaseApplyById(map);
		String gd_id = String.valueOf(purchaseApplyMap.get("gd_id"));
		List<Map<String,Object>> list = gdMapper.listGDPurchaseApplyDetail(map);
		for(int i=0;i<list.size();i++){
			//更新预算已使用数
			String material_id = String.valueOf(list.get(i).get("material_id"));
			Object num = list.get(i).get("apply_num");
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", gd_id);
			queryMap.put("material_id", material_id);
			queryMap.put("num", num);
			gdMapper.updateAssumeMaterial(queryMap);
		}
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	public String backToGDReturnApply(Map<String,Object> map){
		Calendar now = Calendar.getInstance();
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
		String return_id = String.valueOf(map.get("key"));
		map.put("return_id", return_id);
		Map<String, Object> returnMap = gdMapper.getPurchaseReturnApplyById(map);
		String purchase_id = String.valueOf(returnMap.get("purchase_id"));
		String dept_id = String.valueOf(returnMap.get("dept_id"));
		Map<String,Object> warehouseMap = getWareHouseByDept(dept_id);
		String warehouse_id = String.valueOf(warehouseMap.get("id"));
		
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>>listDetail=gdMapper.listGDPurchaseReturnApplyDetail(map);
		for(int i=0;i<listDetail.size();i++){
			Map<String,Object> m = listDetail.get(i);
			String material_id = String.valueOf(m.get("material_id"));
			BigDecimal num = new BigDecimal(String.valueOf(m.get("apply_num")));
			Map<String,Object> dbMap = getDBMap(material_id,warehouse_id,purchase_id);
			
			if(dbMap != null){
				//订单料库增加
				Map<String,Object>mapDetail=new HashMap<String,Object>();
				Map<String,Object> queryMap = new HashMap<String,Object>();
				queryMap.put("num", num);
				queryMap.put("db_id", dbMap.get("id"));
				wareHouseMapper.addDBNum(queryMap);
				//生成日志
				Map<String,Object> dbLogMap = new HashMap<String,Object>();
				String db_log_id = UUID.randomUUID().toString();
				dbLogMap.put("id", db_log_id);
				dbLogMap.put("warehouse_id", warehouse_id);
				dbLogMap.put("product_id", material_id);
				dbLogMap.put("customer_id", "");
				dbLogMap.put("project_id", "");
				dbLogMap.put("gd_id", purchase_id);
				dbLogMap.put("supplier_id", "");
				dbLogMap.put("num", num);
				dbLogMap.put("cost", dbMap.get("cost"));
				dbLogMap.put("person_id", map.get("person_id"));
				dbLogMap.put("person", map.get("person"));
				dbLogMap.put("operation_date", operation_date);
				dbLogMap.put("direction", StaticData.DB_IN);
				dbLogMap.put("business_type", StaticData.GD_RETURN_APPLY);
				dbLogMap.put("business_id", return_id);
				dbLogMap.put("summary", "工单【"+String.valueOf(returnMap.get("gd_code"))+"】退料【入库】，库存增加");
				dbList.add(dbLogMap);
				
				//更新申请单已领数量
				mapDetail.put("apply_id",returnMap.get("purchase_id"));
				mapDetail.put("material_id", listDetail.get(i).get("material_id"));
				mapDetail.put("apply_num", listDetail.get(i).get("apply_num"));
				gdMapper.subGDPurchaseApplyNum(mapDetail);
			}
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	/**
	 * 工单内容审批
	 * @param map
	 * @return
	 */
	public String backToGDUpdateGDBaseStatus(Map<String,Object> map){
		String gd_content_id = String.valueOf(map.get("key"));
		map.put("gd_content_id", gd_content_id);
		Map<String, Object> contentMap = gdMapper.getGDContentByContentId(map);
		String gd_id = String.valueOf(contentMap.get("gd_id"));
		map.put("gd_id", gd_id);
		map.put("gd_create_time", new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date()));
		gdMapper.updateGDBaseCreateTime(map);
		List<Map<String,Object>> list = gdMapper.listGDContent(map);
		//如果当前工单就一个内容，则更新为“现场交底”，否则“现场交底(变更)”
		if(list.size() > 1){
			map.put("gd_status", StaticData.DESCRIPTION_ADD);
			//并且更新当前的材料预算中的already_use和queue_num为上个内容的预算值
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", gd_id);
			queryMap.put("gd_content_id", list.get(list.size()-2).get("id"));//获取倒数第二个工单内容id
			List<Map<String,Object>> lastAssumeList = gdMapper.listGDAssumeMaterial(queryMap);
			for(int i=0;i<lastAssumeList.size();i++){
				queryMap.put("material_id", lastAssumeList.get(i).get("material_id"));
				BigDecimal zreo = new BigDecimal(0);
				BigDecimal already_use = new BigDecimal(String.valueOf(lastAssumeList.get(i).get("already_use")));//上一次的已使用量
				BigDecimal queue_num = new BigDecimal(String.valueOf(lastAssumeList.get(i).get("queue_num")));//上一次的审批占用量
				if(already_use.compareTo(zreo) > 0 || queue_num.compareTo(zreo) > 0){
					queryMap.put("gd_content_id", gd_content_id);//本次内容id
					queryMap.put("already_use", already_use);
					queryMap.put("queue_num", queue_num);
					gdMapper.updateNewAssumeMaterial(queryMap);
				}
			}
			
		}else{
			map.put("gd_status", StaticData.DESCRIPTION);
		}
		workFlowMapper.backToGDUpdateGDBaseStatus(map);
		//如果工单有项目，要更新项目的工单数量和开工时间
		Map<String,Object> gdBaseMap = gdMapper.getGDBaseById(map);
		String xm_id = String.valueOf(gdBaseMap.get("xm_id"));
		if(!xm_id.equals("null") && !"".equals(xm_id)){
			map.put("xm_id", xm_id);
			xmAssistService.updateXMProgressStatusByGD(map);
			xmAssistService.updateStartTimeAndGDSetByXM(map);
		}
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	/**
	 * 现场利旧
	 * @param map
	 * @return
	 */
	public String backToGDReuse(Map<String,Object> map){
		String reuse_id = String.valueOf(map.get("key"));
		map.put("reuse_id", reuse_id);
		Map<String,Object> reuseMap = gdMapper.getReuseById(map);
		String gd_id = String.valueOf(reuseMap.get("gd_id"));
		map.put("gd_id", gd_id);
		List<Map<String,Object>> list = gdMapper.listGDReuseDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			m.put("gd_id", gd_id);
			gdMapper.updateAssumeMaterial(m);
		}
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	/**
	 * 项目报账审核通过之后更新项目借款报账金额
	 * @param map
	 * @return
	 */
	public String backToUpdateXMBz(Map<String,Object> map){
		String rem_id = String.valueOf(map.get("key"));
		map.put("rem_id", rem_id);
		Map<String, Object> remMap = xmFinanceMapper.getReimbursementById(map);
		if(remMap!=null){
			Map<String,Object>mapRem=new HashMap<String,Object>();
			mapRem.put("xm_id",remMap.get("xm_id"));
			if("1".equals(String.valueOf(remMap.get("is_borrow")))){
				mapRem.put("loan_reimburs",remMap.get("reimbursement"));
				mapRem.put("xm_envelopes_id", rem_id);
				mapRem.put("yet", "1");
				List<Map<String,Object>>loanList=xmFinanceMapper.getXmRemLoanById(map);//查询出借款信息
				for(int i=0;i<loanList.size();i++){
					mapRem.put("already_money", loanList.get(i).get("alreadyMoney"));
					mapRem.put("loan_id", loanList.get(i).get("id"));
					xmFinanceMapper.updateXmRemLoan(mapRem); 
				}
				xMAssistMapper.addXMLoanReimburs(mapRem);
			}else{
				mapRem.put("direct_reimburse",remMap.get("reimbursement"));
				BigDecimal reimbursement = new BigDecimal(String.valueOf(remMap.get("reimbursement")));
				xMAssistMapper.addXMDirectReimburse(mapRem);
			}
		}
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	/**
	 * 甲供项目库领料
	 * @param map
	 * @return
	 */
	public String backToGDJgRequest(Map<String,Object> map){
		Calendar now = Calendar.getInstance();
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
		String req_id = String.valueOf(map.get("key"));
		map.put("id", req_id);
		Map<String, Object> jgRequestMap = gdMapper.getJgRequestById(map);
		map.put("req_id", req_id);
		List<Map<String,Object>> jgRequestDetailList = gdMapper.listGDJgRequestDetail(map);
		String dept_id = String.valueOf(jgRequestMap.get("dept_id"));
		//1.先获取当前部门的工余库
		Map<String,Object> queryParam = new HashMap<String,Object>();
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		Map<String,Object> mapGx=gdMapper.getXmBygdId(jgRequestMap);
		queryParam.put("dept_id", dept_id);
		queryParam.put("project_id", mapGx.get("xm_id"));
		queryParam.put("type", 1);//1：甲供库
		for(int i=0;i<jgRequestDetailList.size();i++){
			Map<String,Object> m = jgRequestDetailList.get(i);
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			String db_log_id = UUID.randomUUID().toString();
			queryParam.put("product_id", m.get("material_id"));
			Map<String,Object> myJgMaterialMap= wareHouseMapper.getJgMaterial(queryParam);
			dbLogMap.put("id", db_log_id);
			dbLogMap.put("warehouse_id", myJgMaterialMap.get("warehouse_id"));
			dbLogMap.put("product_id", m.get("material_id"));
			dbLogMap.put("customer_id", "");
			dbLogMap.put("project_id", mapGx.get("xm_id"));
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("num", m.get("req_num"));
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_OUT);
			dbLogMap.put("business_type", StaticData.XM_JG_OUT_DB);
			dbLogMap.put("business_id", req_id);
			dbLogMap.put("summary", "工单【"+String.valueOf(jgRequestMap.get("gd_code"))+"】领【"+String.valueOf(mapGx.get("xm_code"))+"】料，库存减少");
			dbList.add(dbLogMap);
			Map<String,Object> dbMap = new HashMap<String,Object>();
			Map<String,Object> mapWare = wareHouseMapper.getMaterialDbById(dbLogMap);
			dbMap.put("db_id",mapWare.get("id"));
			dbMap.put("num", m.get("req_num"));
			wareHouseMapper.subtractDBNum(dbMap);
			wareHouseMapper.subtractQueueNum(dbMap);
			
			//更新预算已使用数
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", jgRequestMap.get("gd_id"));
			queryMap.put("material_id", m.get("material_id"));
			queryMap.put("num", m.get("req_num"));
			gdMapper.updateAssumeMaterial(queryMap);
			
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	public String backToGDSelfRequest(Map<String,Object> map){
		Calendar now = Calendar.getInstance();
		String operation_date1 = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
		String request_id = String.valueOf(map.get("key"));
		map.put("id", request_id);
		Map<String, Object> selfRequestMap = gdMapper.getSelfRequestById(map);
		map.put("request_id", request_id);
		List<Map<String,Object>> selfRequestDetailList = gdMapper.listGDSelfRequestDetail(map);
		String gd_id = String.valueOf(selfRequestMap.get("gd_id"));
		for(int i = 0;i < selfRequestDetailList.size();i++){
			Map<String,Object> selfRequestDetailMap = selfRequestDetailList.get(i);
			BigDecimal num = new BigDecimal(String.valueOf(selfRequestDetailMap.get("num")));
			String material_id = String.valueOf(selfRequestDetailMap.get("material_id"));
			
			//更新预算审核占用值-----start
			Map<String,Object> assumMap = new HashMap<String,Object>();
			assumMap.put("gd_id", gd_id);
			assumMap.put("material_id", material_id);
			assumMap.put("num", num);
			gdMapper.updateAssumeMaterial(assumMap);
			//更新预算审核占用值-----end
		}
		String dept_id = String.valueOf(selfRequestMap.get("dept_id"));
		
		//从本部门中减去本次申请单的总额，摘要为本次工单的领用描述----start
		subTotal(operation_date1, map, request_id, dept_id, selfRequestMap, selfRequestDetailList);
		//从本部门中减去本次申请单的总额，摘要为本次工单的领用描述----end
		
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		//获取分配规则
		map.put("gd_id", gd_id);
		List<Map<String,Object>> fpList = gdMapper.getSelfRequestFP(map);
		for(int i=0;i<fpList.size();i++){
				now.add(Calendar.SECOND, 1);
				String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
				Map<String,Object> m = fpList.get(i);
				String db_id = String.valueOf(m.get("db_id"));
				String action_dept_id = String.valueOf(m.get("dept_id"));
				BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
				BigDecimal cost = new BigDecimal(String.valueOf(m.get("cost")));
				
				Map<String,Object> dbMap = wareHouseMapper.getDBById(m);
				String warehouse_id = String.valueOf(dbMap.get("warehouse_id"));
				String material_id = String.valueOf(dbMap.get("product_id"));
				//1.库存减少，生成库存变更日志
				Map<String,Object> queryMap = new HashMap<String,Object>();
				queryMap.put("db_id", db_id);
				queryMap.put("num", num);
				wareHouseMapper.subtractDBNum(queryMap);
				//更新审批占用值
				BigDecimal zero = new BigDecimal(0);
				queryMap.put("num", zero.subtract(num));
				wareHouseMapper.updateQueueMaterial(queryMap);
				
				Map<String,Object> dbLogMap = new HashMap<String,Object>();
				String db_log_id = UUID.randomUUID().toString();
				dbLogMap.put("id", db_log_id);
				dbLogMap.put("warehouse_id", warehouse_id);
				dbLogMap.put("customer_id", "");
				dbLogMap.put("project_id", "");
				dbLogMap.put("gd_id", "");
				dbLogMap.put("supplier_id", "");
				dbLogMap.put("product_id", material_id);
				dbLogMap.put("cost", cost);
				dbLogMap.put("num", num);
				dbLogMap.put("person_id", map.get("person_id"));
				dbLogMap.put("person", map.get("person"));
				dbLogMap.put("operation_date", operation_date);
				dbLogMap.put("direction", StaticData.DB_OUT);
				dbLogMap.put("business_type", StaticData.GD_SELF_REQUEST);
				dbLogMap.put("business_id", request_id);//业务id为工单的领用申请
				dbLogMap.put("summary", "工单【"+String.valueOf(selfRequestMap.get("gd_code"))+"】领工余料，库存减少");
				dbList.add(dbLogMap);
				//2.部门的金额增加，生成金额变更日志
				Map<String,Object> fd = financeMapper.getFinanceDeptByDeptId(action_dept_id);//获取该部门的账户信息
				Map<String,Object> financeMap = new HashMap<String,Object>();
				financeMap.put("finance_dept_id", fd.get("id"));
				financeMap.put("type", StaticData.FINANCE_IN);
				financeMap.put("summary", "工余库材料出库收入");
				financeMap.put("proof_type", StaticData.Proof_Self_DB_Out);
				financeMap.put("proof_id", db_log_id);
				financeMap.put("before_money", fd.get("money"));
				financeMap.put("money", num.multiply(cost));
				financeMap.put("person_id", map.get("person_id"));
				financeMap.put("person", map.get("person"));
				financeMap.put("operation_date", operation_date);
				financeMapper.addFinanceDeptMoney(financeMap);
				financeMapper.addFinanceDeptLog(financeMap);
			}
		wareHouseMapper.addDBLog1(dbList);
		gdMapper.deleteSelfRequestFP(map);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	private void subTotal(String operation_date1,Map<String,Object> map,String request_id,String dept_id,Map<String,Object> selfRequestMap,List<Map<String,Object>> selfRequestDetailList){
		Map<String,Object> financeDept = financeMapper.getFinanceDeptByDeptId(dept_id);//获取该部门的账户信息
		Map<String,Object> myDeptFinanceMap = new HashMap<String,Object>();
		myDeptFinanceMap.put("finance_dept_id", financeDept.get("id"));
		myDeptFinanceMap.put("type", StaticData.FINANCE_OUT);
		myDeptFinanceMap.put("summary", "工单【"+String.valueOf(selfRequestMap.get("gd_code"))+"】领用工余库材料，支出金额");
		myDeptFinanceMap.put("proof_type", StaticData.Proof_Self_Request);
		myDeptFinanceMap.put("proof_id", request_id);
		myDeptFinanceMap.put("before_money", financeDept.get("money"));
		myDeptFinanceMap.put("money", getTotalMoney(selfRequestDetailList));
		myDeptFinanceMap.put("person_id", map.get("person_id"));
		myDeptFinanceMap.put("person", map.get("person"));
		myDeptFinanceMap.put("operation_date", operation_date1);
		financeMapper.subFinanceDeptMoney(myDeptFinanceMap);
		financeMapper.addFinanceDeptLog(myDeptFinanceMap);
	}
	private BigDecimal getTotalMoney(List<Map<String,Object>> selfRequestDetailList){
		BigDecimal totalMoney = new BigDecimal("0");
		for(int i=0;i<selfRequestDetailList.size();i++){
			Map<String,Object> selfRequestDetailMap = selfRequestDetailList.get(i);
			BigDecimal num = new BigDecimal(String.valueOf(selfRequestDetailMap.get("num")));
			BigDecimal cost = new BigDecimal(String.valueOf(selfRequestDetailMap.get("cost")));
			totalMoney = totalMoney.add(num.multiply(cost));
		}
		return totalMoney;
	}
//	private List<Map<String,Object>> operateMyInfo(List<Map<String,Object>> dbList,Map<String,Object> selfRequestMap,Map<String,Object> mySelfMaterialMap,String dept_id,BigDecimal num,BigDecimal cost,String material_id,Map<String,Object> map,String operation_date,String request_id){
//		Map<String,Object> financeDept = financeMapper.getFinanceDeptByDeptId(dept_id);//获取该部门的账户信息
//		
//		//1.库存减少，生成库存变更日志
//		mySelfMaterialMap.put("num", num);
//		//1.库存减少，生成库存变更日志
//		wareHouseMapper.subtractDBNum(mySelfMaterialMap);
//		Map<String,Object> dbLogMap = new HashMap<String,Object>();
//		String db_log_id = UUID.randomUUID().toString();
//		dbLogMap.put("id", db_log_id);
//		dbLogMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
//		dbLogMap.put("customer_id", "");
//		dbLogMap.put("project_id", "");
//		dbLogMap.put("gd_id", "");
//		dbLogMap.put("supplier_id", "");
//		dbLogMap.put("product_id", material_id);
//		dbLogMap.put("cost", cost);
//		dbLogMap.put("num", num);
//		dbLogMap.put("person_id", map.get("person_id"));
//		dbLogMap.put("person", map.get("person"));
//		dbLogMap.put("operation_date", operation_date);
//		dbLogMap.put("direction", StaticData.DB_OUT);
//		dbLogMap.put("business_type", StaticData.GD_SELF_REQUEST);
//		dbLogMap.put("business_id", request_id);//业务id为工单的领用申请
//		dbLogMap.put("summary", "工单【"+String.valueOf(selfRequestMap.get("gd_code"))+"】领【"+String.valueOf(selfRequestMap.get("dept_name"))+"】料，库存减少");
//		dbList.add(dbLogMap);
//		//2.部门的金额增加，生成金额变更日志
//		Map<String,Object> financeMap = new HashMap<String,Object>();
//		financeMap.put("finance_dept_id", financeDept.get("id"));
//		financeMap.put("type", StaticData.FINANCE_IN);
//		financeMap.put("summary", "工余库材料出库收入");
//		financeMap.put("proof_type", StaticData.Proof_Self_DB_Out);
//		financeMap.put("proof_id", db_log_id);
//		financeMap.put("before_money", financeDept.get("money"));
//		financeMap.put("money", num.multiply(cost));
//		financeMap.put("person_id", map.get("person_id"));
//		financeMap.put("person", map.get("person"));
//		financeMap.put("operation_date", operation_date);
//		financeMapper.addFinanceDeptMoney(financeMap);
//		financeMapper.addFinanceDeptLog(financeMap);
//		return dbList;
//	}
	/**
	 * 过滤其他部门的工余量信息，返回我要的部门和真实使用量信息
	 * @param num
	 * @param queryParam
	 * @return
	 */
//	private List<Map<String,Object>> getMaterialOtherSelfDB(BigDecimal num,Map<String,Object> queryParam){
//		List<Map<String,Object>> rtList = new ArrayList<Map<String,Object>>();
//		List<Map<String,Object>> otherDeptselfList = wareHouseMapper.getMaterialOtherSelfDB(queryParam);
//		for(int i=0;i<otherDeptselfList.size();i++){
//			Map<String,Object> map = otherDeptselfList.get(i);
//			BigDecimal otherNum = new BigDecimal(String.valueOf(map.get("num")));
//			if(num.compareTo(otherNum) == 1){
//				rtList.add(map);
//				num = num.subtract(otherNum);
//			}else{
//				map.put("num",num);
//				rtList.add(map);
//				break;
//			}
//		}
//		return rtList;
//	}
//	
	public String backToGDRecoveryMaterial(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String recovery_id = String.valueOf(map.get("key"));
		map.put("recovery_id", recovery_id);
		Map<String, Object> recoveryMap = gdMapper.getRecoveryById(map);
		String dept_id = String.valueOf(recoveryMap.get("dept_id"));
		List<Map<String,Object>> list = gdMapper.listGDRecoveryDetail(map);
		
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		//将拆旧回收料入部门工余库,价格按照加权平均算。
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			String material_id = String.valueOf(m.get("material_id"));
			
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			String db_log_id = UUID.randomUUID().toString();
			dbLogMap.put("id", db_log_id);
			
			//1.先获取当前部门的工余库
			Map<String,Object> queryParam = new HashMap<String,Object>();
			queryParam.put("dept_id", dept_id);
			queryParam.put("type", 2);//2：工余库
			queryParam.put("product_id", material_id);
			Map<String,Object> mySelfMaterialMap= wareHouseMapper.getMySelfMaterial(queryParam);
			if(mySelfMaterialMap == null){
				//表示当前该部门没有该材料记录,则添加该记录
				List<Map<String,Object>> dbl = new ArrayList<Map<String,Object>>();
				Map<String,Object> dbMap = new HashMap<String,Object>();
				String warehouse_id = wareHouseMapper.getMySelfWarehouseByDeptId(dept_id);
				dbMap.put("warehouse_id", warehouse_id);
				dbLogMap.put("warehouse_id", warehouse_id);
				dbMap.put("product_id", material_id);
				dbMap.put("cost", m.get("cost"));
				dbMap.put("num", m.get("num"));
				dbMap.put("top", 1000);
				dbMap.put("low", 0);
				dbl.add(dbMap);
				wareHouseMapper.addMyMaterialDB(dbl);
			}else{
				//获取该产品所有的库存数量和单价
				Map<String,Object> productDBMap = wareHouseMapper.getSelfProductDB(queryParam);
				if(productDBMap == null){
					queryParam.put("cost", m.get("cost"));
				}else{
					//加权平均
					BigDecimal oldCost = new BigDecimal(String.valueOf(productDBMap.get("cost")));
					BigDecimal money = new BigDecimal(0);
					if(oldCost.compareTo(money)==0){
						queryParam.put("cost", m.get("cost"));
					}else{
					BigDecimal oldNum = new BigDecimal(String.valueOf(productDBMap.get("num")));
					BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
					BigDecimal cost = new BigDecimal(String.valueOf(m.get("cost")));
					BigDecimal newCost = oldNum.multiply(oldCost).add(num.multiply(cost)).divide(oldNum.add(num),2,BigDecimal.ROUND_HALF_DOWN);
					queryParam.put("cost", newCost);
					}
					wareHouseMapper.updateSelfCost(queryParam);
				}
				//库存增加，生成库存变更日志
				m.put("db_id", mySelfMaterialMap.get("db_id"));
				wareHouseMapper.addDBNum(m);
				dbLogMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
			}
			dbLogMap.put("customer_id", "");
			dbLogMap.put("project_id", "");
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("product_id", material_id);
			dbLogMap.put("num", m.get("num"));
			dbLogMap.put("cost", m.get("cost"));
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_IN);
			dbLogMap.put("business_type", StaticData.GD_RECOVERY);
			dbLogMap.put("business_id", recovery_id);
			dbLogMap.put("summary", "工单【"+String.valueOf(recoveryMap.get("gd_code"))+"】拆旧回收【"+String.valueOf(recoveryMap.get("dept_name"))+"】，库存增加");
			dbList.add(dbLogMap);
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	public String backToGDBorrowCustomer(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String borrow_id = String.valueOf(map.get("key"));
		map.put("borrow_id", borrow_id);
		Map<String,Object> borrowMap = gdMapper.getCustomerBorrowById(map);
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> list = gdMapper.listGDCustomerBorrowDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			//从被借的仓库中出料，并生成日志
			wareHouseMapper.borrowCustomerMaterial(m);
			wareHouseMapper.subtractCustomerQueueNum(m);
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			String db_log_id = UUID.randomUUID().toString();
			dbLogMap.put("id", db_log_id);
			dbLogMap.put("warehouse_id", m.get("warehouse_id"));
			dbLogMap.put("customer_id", m.get("customer_id"));
			dbLogMap.put("project_id", "");
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("product_id", m.get("material_id"));
			dbLogMap.put("num", m.get("num"));
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_OUT);
			dbLogMap.put("business_type", StaticData.GD_BORROW_CUSTOMER);
			dbLogMap.put("business_id", borrow_id);
			dbLogMap.put("summary", "工单【"+String.valueOf(borrowMap.get("gd_code"))+"】借【"+getCustomerName(m.get("customer_id"))+"】，库存减少");
			dbList.add(dbLogMap);
			//更新预算已使用数
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", borrowMap.get("gd_id"));
			queryMap.put("material_id", m.get("material_id"));
			queryMap.put("num", m.get("num"));
			gdMapper.updateAssumeMaterial(queryMap);
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	private String getSupplierName(String supplier_id){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", supplier_id);
		return String.valueOf(crmMapper.getSupplierById(map).get("company"));
	}
	private String getCustomerName(Object customer_id){
		Map<String,Object> map =  new HashMap<String,Object>();
		map.put("id", customer_id);
		return String.valueOf(crmMapper.getCustomerById(map).get("company"));
	}
	public String backToGDReturnCustomer(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String return_id = String.valueOf(map.get("key"));
		map.put("return_id", return_id);
		Map<String,Object> returnMap = gdMapper.getCustomerReturnById(map);
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> list = gdMapper.listGDCustomerReturnDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			BigDecimal return_num = new BigDecimal(String.valueOf(m.get("return_num")));
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", m.get("gd_id"));
			queryMap.put("material_id", m.get("material_id"));
			Map<String,Object> projectDB = gdMapper.getProjectMaterialDB(queryMap);//根据当前工单所属的项目，及材料找到该项目库中材料记录
			projectDB.put("db_id", projectDB.get("id"));
			projectDB.put("num", return_num);
			wareHouseMapper.subtractDBNum(projectDB);//减去项目库中欠的材料
			
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			dbLogMap.put("id", UUID.randomUUID().toString());
			dbLogMap.put("warehouse_id", projectDB.get("warehouse_id"));
			dbLogMap.put("product_id", projectDB.get("product_id"));
			dbLogMap.put("customer_id", "");
			dbLogMap.put("project_id", projectDB.get("project_id"));
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("num", return_num);
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_OUT);
			dbLogMap.put("business_type", StaticData.GD_REQUEST_FOR_CUSTOMER_RETURN);
			dbLogMap.put("business_id", return_id);
			Map<String,Object> mapGx=gdMapper.getXmBygdId(queryMap);
			dbLogMap.put("summary", "项目【"+String.valueOf(returnMap.get("xm_code"))+"】领【"+String.valueOf(mapGx.get("xm_code"))+"】料(还客户料)，库存减少");
			dbList.add(dbLogMap);
			//项目库减少，并生成日志
			
			//被借库，库存增加，并生成日志
			Map<String,Object> borrowMap = gdMapper.getCustomerBorrowDetailById(m);
			m.put("customer_id", borrowMap.get("customer_id"));
			wareHouseMapper.returnCustomerMaterial(m);
			dbLogMap = new HashMap<String,Object>();
			dbLogMap.put("id", UUID.randomUUID().toString());
			dbLogMap.put("warehouse_id", m.get("warehouse_id"));
			dbLogMap.put("customer_id", m.get("customer_id"));
			dbLogMap.put("project_id", "");
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("product_id", m.get("material_id"));
			dbLogMap.put("num", m.get("return_num"));
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_IN);
			dbLogMap.put("business_type", StaticData.GD_RETURN_CUSTOMER);
			dbLogMap.put("business_id", return_id);
			dbLogMap.put("summary", "项目【"+String.valueOf(returnMap.get("xm_code"))+"】还【"+getCustomerName(m.get("customer_id"))+"】，库存增加");
			dbList.add(dbLogMap);
			//更新借料库
			BigDecimal already_return_num = new BigDecimal("0");
			if(borrowMap.get("return_num") != null){
				already_return_num = new BigDecimal(String.valueOf(borrowMap.get("return_num")));
			}
			BigDecimal borrow_num = new BigDecimal(String.valueOf(borrowMap.get("num")));
			if(return_num.add(already_return_num).compareTo(borrow_num) != -1){
				//如果本次还料数量加上已经还料的数量 大于等于 借料数量，则更新被借的材料状态，并且判断当前借料单的状态
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("borrow_detail_id", m.get("borrow_detail_id"));
				updateMap.put("return_num", return_num);
				updateMap.put("return_status", 1);
				gdMapper.updateBorrowDetail(updateMap);
				if(gdMapper.checkAllReturn(borrowMap) <= 0){
					//如果其他材料都还完，则更新借料单状态
					gdMapper.updateBorrowStatus(borrowMap);
				}
			}else{
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("borrow_detail_id", m.get("borrow_detail_id"));
				updateMap.put("return_num", return_num);
				gdMapper.updateBorrowDetail(updateMap);
			}
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	public String backToGDBorrowSelf(Map<String,Object> map){
		Calendar now = Calendar.getInstance();
		String borrow_id = String.valueOf(map.get("key"));
		map.put("borrow_id", borrow_id);
		Map<String,Object> borrowMap = gdMapper.getCustomerBorrowById(map);
		String dept_id = String.valueOf(borrowMap.get("dept_id"));
		
		List<Map<String,Object>> list = gdMapper.listGDCustomerBorrowDetail(map);
		
		for(int i=0;i<list.size();i++){
			now.add(Calendar.SECOND, 1);
			String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
			Map<String,Object> m = list.get(i);
			BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
			BigDecimal cost = new BigDecimal(String.valueOf(m.get("cost")));
			String material_id = String.valueOf(m.get("material_id"));

			//1.先获取当前部门的工余库
			Map<String,Object> queryParam = new HashMap<String,Object>();
			queryParam.put("dept_id", dept_id);
			queryParam.put("type", 2);//2：工余库
			queryParam.put("product_id", material_id);
			Map<String,Object> mySelfMaterialMap= wareHouseMapper.getMySelfMaterial(queryParam);
				//小于等于的时候，直接从本部门中取，不用再查询其他部门的工余
				List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
				List<Map<String,Object>> borrowDetailList = new ArrayList<Map<String,Object>>();
				//1.去除本部门的材料，生成日志
				Map<String,Object> myBorrowDetailMap = new HashMap<String,Object>();
				myBorrowDetailMap.put("borrow_detail_id", m.get("id"));
				myBorrowDetailMap.put("dept_id", mySelfMaterialMap.get("dept_id"));
				myBorrowDetailMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
				myBorrowDetailMap.put("material_id", material_id);
				myBorrowDetailMap.put("num", num);
				mySelfMaterialMap.put("num", num);
				myBorrowDetailMap.put("cost", cost);
				borrowDetailList.add(myBorrowDetailMap);
				wareHouseMapper.subtractDBNum(mySelfMaterialMap);
				wareHouseMapper.subtractQueueNum(mySelfMaterialMap);
				
				Map<String,Object> myDbLogMap = new HashMap<String,Object>();
				String my_db_log_id = UUID.randomUUID().toString();
				myDbLogMap.put("id", my_db_log_id);
				myDbLogMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
				myDbLogMap.put("customer_id", "");
				myDbLogMap.put("project_id", "");
				myDbLogMap.put("gd_id", "");
				myDbLogMap.put("supplier_id", "");
				myDbLogMap.put("product_id", material_id);
				myDbLogMap.put("cost", cost);
				myDbLogMap.put("num", num);
				myDbLogMap.put("person_id", map.get("person_id"));
				myDbLogMap.put("person", map.get("person"));
				myDbLogMap.put("operation_date", operation_date);
				myDbLogMap.put("direction", StaticData.DB_OUT);
				myDbLogMap.put("business_type", StaticData.GD_BORROW_SELF);
				myDbLogMap.put("business_id", borrow_id);
				myDbLogMap.put("summary", "工单【"+String.valueOf(borrowMap.get("gd_code"))+"】借工余库料");
				dbList.add(myDbLogMap);
				wareHouseMapper.addDBLog1(dbList);
				gdMapper.addBorrowDetailForSelf(borrowDetailList);
				
				//更新预算已使用数
				Map<String,Object> queryMap = new HashMap<String,Object>();
				queryMap.put("gd_id", borrowMap.get("gd_id"));
				queryMap.put("material_id", material_id);
				queryMap.put("num", num);
				gdMapper.updateAssumeMaterial(queryMap);
		}
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	public String backToGDReturnSelf(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String return_id = String.valueOf(map.get("key"));
		map.put("return_id", return_id);
		Map<String,Object> returnMap = gdMapper.getCustomerReturnById(map);
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> list = gdMapper.listGDCustomerReturnDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			BigDecimal return_num = new BigDecimal(String.valueOf(m.get("return_num")));
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("gd_id", m.get("gd_id"));
			queryMap.put("material_id", m.get("material_id"));
			Map<String,Object> projectDB = gdMapper.getProjectMaterialDB(queryMap);//根据当前工单所属的项目，及材料找到该项目库中材料记录
			
			projectDB.put("db_id", projectDB.get("id"));
			projectDB.put("num", return_num);
			wareHouseMapper.subtractDBNum(projectDB);//减去项目库中欠的材料
			
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			dbLogMap.put("id", UUID.randomUUID().toString());
			dbLogMap.put("warehouse_id", projectDB.get("warehouse_id"));
			dbLogMap.put("product_id", projectDB.get("product_id"));
			dbLogMap.put("customer_id", "");
			dbLogMap.put("project_id", projectDB.get("project_id"));
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("num", return_num);
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_OUT);
			dbLogMap.put("business_type", StaticData.GD_BORROW_SELF_RETURN);
			dbLogMap.put("business_id", return_id);
			dbLogMap.put("summary", "项目【"+String.valueOf(returnMap.get("xm_code"))+"】还供余料，库存减少");
			dbList.add(dbLogMap);
			//项目库减少，并生成日志
			
			//被借库，库存增加，并生成日志
			Map<String,Object> borrowMap = gdMapper.getCustomerBorrowDetailById(m);
			m.put("product_id", m.get("material_id"));
			wareHouseMapper.returnOtherMaterial(m);
			dbLogMap = new HashMap<String,Object>();
			dbLogMap.put("id", UUID.randomUUID().toString());
			dbLogMap.put("warehouse_id", m.get("warehouse_id"));
			dbLogMap.put("customer_id", m.get("customer_id"));
			dbLogMap.put("project_id", "");
			dbLogMap.put("gd_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("product_id", m.get("material_id"));
			dbLogMap.put("num", m.get("return_num"));
			dbLogMap.put("cost", "0");
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_IN);
			dbLogMap.put("business_type", StaticData.GD_BORROW_SELF_RETURN);
			dbLogMap.put("business_id", return_id);
			dbLogMap.put("summary", "项目【"+String.valueOf(returnMap.get("xm_code"))+"】还供余料，库存增加");
			dbList.add(dbLogMap);
			//更新借料库
			BigDecimal already_return_num = new BigDecimal("0");
			if(borrowMap.get("return_num") != null){
				already_return_num = new BigDecimal(String.valueOf(borrowMap.get("return_num")));
			}
			BigDecimal borrow_num = new BigDecimal(String.valueOf(borrowMap.get("num")));
			if(return_num.add(already_return_num).compareTo(borrow_num) != -1){
				//如果本次还料数量加上已经还料的数量 大于等于 借料数量，则更新被借的材料状态，并且判断当前借料单的状态
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("borrow_detail_id", m.get("borrow_detail_id"));
				updateMap.put("return_num", return_num);
				updateMap.put("return_status", 1);
				gdMapper.updateBorrowDetail(updateMap);
				if(gdMapper.checkAllReturn(borrowMap) <= 0){
					//如果其他材料都还完，则更新借料单状态
					gdMapper.updateBorrowStatus(borrowMap);
				}
			}else{
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("borrow_detail_id", m.get("borrow_detail_id"));
				updateMap.put("return_num", return_num);
				gdMapper.updateBorrowDetail(updateMap);
			}
		}
		wareHouseMapper.addDBLog1(dbList);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	/**
	 * 1.入订单库，产生库存日志
	 * 2.更新订货单的到货数量，更新申请单的到货数量
	 * 3.记供货商应付
	 * @param map
	 * @return
	 */
	public String backToProductIn(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String product_in_id = String.valueOf(map.get("key"));
		map.put("product_in_id", product_in_id);
		Map<String,Object> productInMap = wareHouseMapper.getPurchaseProductInById(map);
		String purchase_id = String.valueOf(productInMap.get("purchase_id"));
		Map<String,Object> purchaseMap = wareHouseMapper.getPurchaseById(productInMap);
		String apply_id = String.valueOf(purchaseMap.get("apply_id"));
		String gd_id = String.valueOf(productInMap.get("gd_id"));
		String supplier_id = String.valueOf(productInMap.get("supplier_id"));
		String supplier = String.valueOf(productInMap.get("supplier"));
		String dept_id = String.valueOf(productInMap.get("gd_dept_id"));
		Map<String,Object> warehouseMap = getWareHouseByDept(dept_id);
		String warehouse_id = String.valueOf(warehouseMap.get("id"));
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		
		List<Map<String,Object>> list = wareHouseMapper.listPurchaseProductInDetail(map);
		BigDecimal finance_out = new BigDecimal(0);
		for(int i=0;i<list.size();i++){
			Map<String,Object> dbLogMap = new HashMap<String,Object>();
			
			Map<String,Object> piMap = list.get(i);
			BigDecimal num = new BigDecimal(String.valueOf(piMap.get("inNum")));
			
			String material_id = String.valueOf(piMap.get("material_id"));
			Map<String,Object> purchaseDetailMap = getPurchaseDetail(material_id,purchase_id); //订货单中该材料的记录
			BigDecimal cost = new BigDecimal(String.valueOf(purchaseDetailMap.get("cost")));
			
			finance_out = finance_out.add(num.multiply(cost));
			
			Map<String,Object> dbMap = getDBMap(material_id,warehouse_id,apply_id);
			//1.入订单库，产生库存日志
			if(dbMap == null){
				//表示当前申请单还没有库存记录，增加库存
				dbMap = new HashMap<String,Object>();
				dbMap.put("warehouse_id", warehouse_id);
				dbMap.put("product_id", material_id);
				dbMap.put("gd_id", apply_id);
				dbMap.put("num", piMap.get("inNum"));
				dbMap.put("cost", cost);
				wareHouseMapper.addPurchaseApplyDB(dbMap);
			}else{
				//更新库存
				dbMap.put("num", piMap.get("inNum"));
				dbMap.put("cost", cost);
				wareHouseMapper.updatePurchaseApplyDB(dbMap);
			}
			String db_log_id = UUID.randomUUID().toString();
			dbLogMap.put("id", db_log_id);
			dbLogMap.put("product_id", material_id);
			dbLogMap.put("warehouse_id", warehouse_id);
			dbLogMap.put("customer_id", "");
			dbLogMap.put("supplier_id", "");
			dbLogMap.put("project_id", "");
			dbLogMap.put("gd_id", apply_id);
			dbLogMap.put("num", piMap.get("inNum"));
			dbLogMap.put("cost", purchaseDetailMap.get("cost"));
			dbLogMap.put("person_id", map.get("person_id"));
			dbLogMap.put("person", map.get("person"));
			dbLogMap.put("operation_date", operation_date);
			dbLogMap.put("direction", StaticData.DB_IN);
			dbLogMap.put("business_type", StaticData.GD_PRODUCT_IN);
			dbLogMap.put("business_id", product_in_id);
			dbLogMap.put("summary", "工单【"+String.valueOf(productInMap.get("gd_code"))+"】采购【入库】，库存增加");
			dbList.add(dbLogMap);
			
			//2.更新订货单的到货数量，更新申请单的到货数量
			updatePurchaseDetailReceiveNum(purchaseDetailMap.get("id"),piMap.get("inNum"));
			updatePurchaseApplyDetailReceiveNum(apply_id,material_id,piMap.get("inNum"));
		}
		wareHouseMapper.addDBLog1(dbList);
		//3.记供货商应付(按照本次入库单计算总额，不对每个材料进行添加，所以放在循环外面)
		Map<String,Object> fodMap = getSupplierFOD(supplier_id,gd_id);
		String detail_id = null;
		BigDecimal before_finance_out = new BigDecimal(0);
		if(fodMap == null){
			fodMap = new HashMap<String,Object>();
			detail_id = UUID.randomUUID().toString();
			fodMap.put("id", detail_id);
			fodMap.put("supplier_id", supplier_id);
			fodMap.put("gd_id", gd_id);
			fodMap.put("finance_out", finance_out);
			crmMapper.addSupplierFOD(fodMap);
		}else{
			before_finance_out = new BigDecimal(String.valueOf(fodMap.get("finance_out")));
			fodMap.put("finance_out", finance_out);
			crmMapper.updateSupplierFOD(fodMap);
			detail_id = String.valueOf(fodMap.get("id"));
		}
		crmMapper.updateSupplierFO(fodMap);
		Map<String,Object> fodLogMap = new HashMap<String,Object>();
		fodLogMap.put("detail_id", detail_id);
		fodLogMap.put("before_finance_out", before_finance_out);
		fodLogMap.put("supplier_id", supplier_id);
		fodLogMap.put("supplier", supplier);
		fodLogMap.put("operation_date", operation_date);
		fodLogMap.put("proof_type", StaticData.CRM_SUPPLIER_PRODUCT_IN);
		fodLogMap.put("proof_id", product_in_id);
		fodLogMap.put("finance_out", finance_out);
		fodLogMap.put("after_finance_out", before_finance_out.add(finance_out));
		fodLogMap.put("summary", "工单【"+String.valueOf(productInMap.get("gd_code"))+"】采购【入库】，应付增加");
		crmMapper.addSupplierFODLog(fodLogMap);
		
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", null);
	}
	
	public String backToGDPurchaseApplyUse(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String apply_use_id = String.valueOf(map.get("key"));
		map.put("apply_use_id", apply_use_id);
		Map<String,Object> applyUseMap = gdMapper.getPurchaseApplyUseById(map);
		
		String apply_id = String.valueOf(applyUseMap.get("apply_id"));
		String dept_id = String.valueOf(applyUseMap.get("dept_id"));
		Map<String,Object> warehouseMap = getWareHouseByDept(dept_id);
		String warehouse_id = String.valueOf(warehouseMap.get("id"));
		
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> list = gdMapper.listGDPurchaseApplyUseDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			String material_id = String.valueOf(m.get("material_id"));
			BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
			Map<String,Object> dbMap = getDBMap(material_id,warehouse_id,apply_id);
			if(dbMap != null){
				//订单料库减少
				Map<String,Object> queryMap = new HashMap<String,Object>();
				queryMap.put("num", num);
				queryMap.put("db_id", dbMap.get("id"));
				wareHouseMapper.subtractDBNum(queryMap);
				//生成日志
				Map<String,Object> dbLogMap = new HashMap<String,Object>();
				String db_log_id = UUID.randomUUID().toString();
				dbLogMap.put("id", db_log_id);
				dbLogMap.put("warehouse_id", warehouse_id);
				dbLogMap.put("product_id", material_id);
				dbLogMap.put("customer_id", "");
				dbLogMap.put("project_id", "");
				dbLogMap.put("gd_id", apply_id);
				dbLogMap.put("supplier_id", "");
				dbLogMap.put("num", num);
				dbLogMap.put("cost", dbMap.get("cost"));
				dbLogMap.put("person_id", map.get("person_id"));
				dbLogMap.put("person", map.get("person"));
				dbLogMap.put("operation_date", operation_date);
				dbLogMap.put("direction", StaticData.DB_OUT);
				dbLogMap.put("business_type", StaticData.GD_PURCHASE_APPLY_USE);
				dbLogMap.put("business_id", apply_use_id);
				dbLogMap.put("summary", "工单【"+String.valueOf(applyUseMap.get("gd_code"))+"】领料【出库】，库存减少");
				dbList.add(dbLogMap);
				
				//更新申请单已领数量
				queryMap.put("apply_id", apply_id);
				queryMap.put("material_id", material_id);
				queryMap.put("used_num", num);
				gdMapper.updatePurchaseApplyDetail(queryMap);
			}
		}
		wareHouseMapper.addDBLog1(dbList);
		return null;
	}
	
	public String backToGDSupplierApply(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String supplier_apply_id = String.valueOf(map.get("key"));
		map.put("supplier_apply_id", supplier_apply_id);
		Map<String,Object> supplierApplyMap = gdMapper.getSupplierApplyById(map);
		List<Map<String,Object>> dbList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> list = gdMapper.listGDSupplierApplyDetail(map);
		for(int i=0;i<list.size();i++){
			Map<String,Object> m = list.get(i);
			String material_id = String.valueOf(m.get("material_id"));
			String supplier_id = String.valueOf(m.get("supplier_id"));
			BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
			
			Map<String,Object> dbMap = getSupplierDBMap(material_id,supplier_id);
			if(dbMap != null){
				//厂家库减少
				Map<String,Object> queryMap = new HashMap<String,Object>();
				queryMap.put("num", num);
				queryMap.put("db_id", dbMap.get("id"));
				wareHouseMapper.subtractDBNum(queryMap);
				wareHouseMapper.subtractQueueNum(queryMap);
				//生成日志
				Map<String,Object> dbLogMap = new HashMap<String,Object>();
				String db_log_id = UUID.randomUUID().toString();
				dbLogMap.put("id", db_log_id);
				dbLogMap.put("warehouse_id", dbMap.get("warehouse_id"));
				dbLogMap.put("product_id", material_id);
				dbLogMap.put("customer_id", "");
				dbLogMap.put("project_id", "");
				dbLogMap.put("gd_id", "");
				dbLogMap.put("supplier_id", supplier_id);
				dbLogMap.put("num", num);
				dbLogMap.put("cost", dbMap.get("cost"));
				dbLogMap.put("person_id", map.get("person_id"));
				dbLogMap.put("person", map.get("person"));
				dbLogMap.put("operation_date", operation_date);
				dbLogMap.put("direction", StaticData.DB_OUT);
				dbLogMap.put("business_type", StaticData.GD_SUPPLIER_APPLY);
				dbLogMap.put("business_id", supplier_apply_id);
				dbLogMap.put("summary", "工单【"+String.valueOf(supplierApplyMap.get("gd_code"))+"】领料【"+String.valueOf(m.get("supplier"))+"】，库存减少");
				dbList.add(dbLogMap);
				
				//更新预算已使用数
				queryMap = new HashMap<String,Object>();
				queryMap.put("gd_id", supplierApplyMap.get("gd_id"));
				queryMap.put("material_id", material_id);
				queryMap.put("num", num);
				gdMapper.updateAssumeMaterial(queryMap);
			}
		}
		wareHouseMapper.addDBLog1(dbList);
		return null;
	}
	/**
	 * 1.材料平衡后，采购的材料如果没有用完要自动到该部门的工余库中，即审批后，要将订单料库的材料转到工余库中去。
	 * 2.分包结算后，要更新对应分包商该工单的应付金额，并生成流水。
	 * 3.审批通过后，将工单的状态为关闭
	 * @param map
	 * @return
	 */
	public String backToGDBalance(Map<String,Object> map){
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		String gd_id = String.valueOf(map.get("key"));
		map.put("gd_id", gd_id);
		Map<String,Object> gdMap = gdMapper.getGDBaseById(map);
		String dept_id = String.valueOf(gdMap.get("dept_id"));
		//1.订单余料入工余库
		List<Map<String,Object>> selfDBList = new ArrayList<Map<String,Object>>();//工余库日志
		List<Map<String,Object>> orderDBList = new ArrayList<Map<String,Object>>();//订单库日志
		
		List<Map<String,Object>> orderList = wareHouseMapper.getOrderLeft(map);//订单库剩余材料
		if(orderList != null && orderList.size() > 0){
			for(int i=0;i<orderList.size();i++){
				Map<String,Object> selfDBMap = new HashMap<String,Object>();//工余库日志
				Map<String,Object> orderDBMap = new HashMap<String,Object>();//订单库日志
				selfDBMap.put("id", UUID.randomUUID().toString());
				orderDBMap.put("id", UUID.randomUUID().toString());
				
				Map<String,Object> m = orderList.get(i);
				Map<String,Object> queryParam = new HashMap<String,Object>();
				queryParam.put("dept_id", dept_id);
				queryParam.put("type", 2);//2：工余库
				queryParam.put("product_id", m.get("product_id"));
				Map<String,Object> mySelfMaterialMap= wareHouseMapper.getMySelfMaterial(queryParam);
				
				if(mySelfMaterialMap == null){
					//表示当前该部门没有该材料记录,则添加该记录
					List<Map<String,Object>> dbl = new ArrayList<Map<String,Object>>();
					Map<String,Object> dbMap = new HashMap<String,Object>();
					String warehouse_id = wareHouseMapper.getMySelfWarehouseByDeptId(dept_id);
					dbMap.put("warehouse_id", warehouse_id);
					dbMap.put("product_id", m.get("product_id"));
					dbMap.put("cost", m.get("cost"));
					dbMap.put("num", m.get("num"));
					dbMap.put("top", 1000);
					dbMap.put("low", 0);
					dbl.add(dbMap);
					wareHouseMapper.addMyMaterialDB(dbl);//工余库增加
					m.put("db_id", m.get("id"));
					wareHouseMapper.subtractDBNum(m);//订单库减少
					//产生日志
					selfDBMap.put("warehouse_id", warehouse_id);
					orderDBMap.put("warehouse_id", m.get("warehouse_id"));
				}else{
					//获取该产品所有的库存数量和单价
					Map<String,Object> productDBMap = wareHouseMapper.getSelfProductDB(queryParam);
					if(productDBMap == null){
						queryParam.put("cost", m.get("cost"));
					}else{
						BigDecimal oldCost = new BigDecimal(String.valueOf(productDBMap.get("cost")));
						BigDecimal money = new BigDecimal(0);
						if(oldCost.compareTo(money)==0){
							queryParam.put("cost", m.get("cost"));
						}else{
						//加权平均
						BigDecimal oldNum = new BigDecimal(String.valueOf(productDBMap.get("num")));
						BigDecimal num = new BigDecimal(String.valueOf(m.get("num")));
						BigDecimal cost = new BigDecimal(String.valueOf(m.get("cost")));
						BigDecimal newCost = oldNum.multiply(oldCost).add(num.multiply(cost)).divide(oldNum.add(num),2,BigDecimal.ROUND_HALF_DOWN);
						queryParam.put("cost", newCost);
						}
						wareHouseMapper.updateSelfCost(queryParam);
					}
					//库存增加，生成库存变更日志
					m.put("db_id", mySelfMaterialMap.get("db_id"));
					wareHouseMapper.addDBNum(m);//工余库增加
					selfDBMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
					m.put("db_id", m.get("id"));
					wareHouseMapper.subtractDBNum(m);//订单库减少
					orderDBMap.put("warehouse_id", m.get("warehouse_id"));
				}
				selfDBMap.put("customer_id", "");
				selfDBMap.put("project_id", "");
				selfDBMap.put("gd_id", "");
				selfDBMap.put("supplier_id", "");
				selfDBMap.put("product_id", m.get("product_id"));
				selfDBMap.put("num", m.get("num"));
				selfDBMap.put("cost", m.get("cost"));
				selfDBMap.put("person_id", map.get("person_id"));
				selfDBMap.put("person", map.get("person"));
				selfDBMap.put("operation_date", operation_date);
				selfDBMap.put("direction", StaticData.DB_IN);
				selfDBMap.put("business_type", StaticData.GD_BALANCE_IN);
				selfDBMap.put("business_id", "");//无业务展示
				selfDBMap.put("summary", "工单【"+String.valueOf(gdMap.get("gd_code"))+"】平衡后订单余料入工余库，库存增加");
				selfDBList.add(selfDBMap);
				
				orderDBMap.put("customer_id", "");
				orderDBMap.put("project_id", "");
				orderDBMap.put("gd_id", m.get("gd_id"));
				orderDBMap.put("supplier_id", "");
				orderDBMap.put("product_id", m.get("product_id"));
				orderDBMap.put("num", m.get("num"));
				orderDBMap.put("cost", m.get("cost"));
				orderDBMap.put("person_id", map.get("person_id"));
				orderDBMap.put("person", map.get("person"));
				orderDBMap.put("operation_date", operation_date);
				orderDBMap.put("direction", StaticData.DB_OUT);
				orderDBMap.put("business_type", StaticData.GD_BALANCE_OUT);
				orderDBMap.put("business_id", "");//无业务展示
				orderDBMap.put("summary", "工单【"+String.valueOf(gdMap.get("gd_code"))+"】平衡后订单余料入工余库，库存减少");
				orderDBList.add(orderDBMap);
			}
			wareHouseMapper.addDBLog1(selfDBList);
			wareHouseMapper.addDBLog1(orderDBList);
		}
		
		//2.分包结算后，要更新对应分包商该工单的应付金额，并生成流水。
		
		//获取该工单的分包结算实际应付
		Map<String,Object> fbMoneyMap = gdMapper.getFBMoney(map);
		String worker_id = String.valueOf(fbMoneyMap.get("gd_worker_id"));
		String worker = String.valueOf(fbMoneyMap.get("gd_worker_name"));
		
		Map<String,Object> fodMap = getWorkerFOD(worker_id,gd_id);
		String detail_id = null;
		BigDecimal before_finance_out = new BigDecimal(0);
		BigDecimal finance_out = new BigDecimal(String.valueOf(fbMoneyMap.get("worker_pay")));
		if(fodMap == null){
			fodMap = new HashMap<String,Object>();
			detail_id = UUID.randomUUID().toString();
			fodMap.put("id", detail_id);
			fodMap.put("worker_id", worker_id);
			fodMap.put("gd_id", gd_id);
			fodMap.put("finance_out", finance_out);
			crmMapper.addWorkerFOD(fodMap);
		}else{
			before_finance_out = new BigDecimal(String.valueOf(fodMap.get("finance_out")));
			fodMap.put("finance_out", finance_out);
			crmMapper.updateWorkerFOD(fodMap);
			detail_id = String.valueOf(fodMap.get("id"));
		}
		crmMapper.updateWorkerFO(fodMap);
		Map<String,Object> fodLogMap = new HashMap<String,Object>();
		fodLogMap.put("detail_id", detail_id);
		fodLogMap.put("before_finance_out", before_finance_out);
		fodLogMap.put("worker_id", worker_id);
		fodLogMap.put("worker", worker);
		fodLogMap.put("operation_date", operation_date);
		fodLogMap.put("proof_type", StaticData.GD_BALANCE);
		fodLogMap.put("proof_id", gd_id);
		fodLogMap.put("finance_out", fbMoneyMap.get("worker_pay"));
		fodLogMap.put("after_finance_out", before_finance_out.add(finance_out));
		fodLogMap.put("summary", "工单【"+String.valueOf(gdMap.get("gd_code"))+"】平衡后成本固化，应付增加");
		crmMapper.addWorkerFODLog(fodLogMap);
		
		//3.审批通过后，将工单的状态为关闭
		map.put("status", StaticData.CLOSED);
		gdMapper.updateGDStatus(map);
		map.put("gd_close_time", operation_date);
		gdMapper.updateGDCloseTime(map);
		return null;
	}
	
	private void updatePurchaseDetailReceiveNum(Object purchase_detail_id,Object receive_num){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("id", purchase_detail_id);
		queryMap.put("receive_num", receive_num);
		wareHouseMapper.updatePurchaseDetailReceiveNum(queryMap);
	}
	private void updatePurchaseApplyDetailReceiveNum(String apply_id,String material_id,Object receive_num){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("apply_id", apply_id);
		queryMap.put("material_id", material_id);
		queryMap.put("receive_num", receive_num);
		wareHouseMapper.updatePurchaseApplyDetailReceiveNum(queryMap);
	}
	private Map<String,Object> getSupplierFOD(String supplier_id,String gd_id){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("supplier_id", supplier_id);
		queryMap.put("gd_id", gd_id);
		return crmMapper.getSupplierFOD(queryMap);
	}
	private Map<String,Object> getWorkerFOD(String worker_id,String gd_id){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("worker_id", worker_id);
		queryMap.put("gd_id", gd_id);
		return crmMapper.getWorkerFOD(queryMap);
	}
	private Map<String,Object> getPurchaseDetail(String material_id,String purchase_id){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("material_id", material_id);
		queryMap.put("purchase_id", purchase_id);
		return wareHouseMapper.getPurchaseDetail(queryMap);
	}
	private Map<String,Object> getDBMap(String material_id,String warehouse_id,String apply_id){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("warehouse_id", warehouse_id);
		queryMap.put("gd_id", apply_id);
		queryMap.put("product_id", material_id);
		return wareHouseMapper.getDBInfo(queryMap);
	}
	private Map<String,Object> getSupplierDBMap(String material_id,String supplier_id){
		Map<String,Object>  queryMap = new HashMap<String,Object>();
		queryMap.put("material_id", material_id);
		queryMap.put("supplier_id", supplier_id);
		return wareHouseMapper.getSupplierDBMap(queryMap);
	}
	private Map<String,Object> getWareHouseByDept(String dept_id){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("dept_id", dept_id);
		map.put("type", 3);
		return wareHouseMapper.getWareHouseByDept(map);
	}
	public int getBusinessFlow(Map<String,Object> map){
     int flow_run_id=0;
    Map m=workFlowMapper.getBusinessFlow(map);
    if(m!=null && m.size()>0){
    	flow_run_id=Integer.valueOf(m.get("flow_run_id").toString());
    }
		return flow_run_id;
	}
	public void addBusinessFlow(Map<String,Object> map){
	    workFlowMapper.addBusinessFlow(map);
	}
	public Map getFlowRunPrcs(Map<String,Object> map){
		return workFlowMapper.getFlowRunPrcs(map);
//		return null;
	}
	public String getFlowView(Map<String,Object> map){
            Map m=workFlowMapper.getBusinessFlow(map);
		return Utility.rtJson(Utility.RETURN_OK, "添加成功", Utility.toJson(m));
	}
	
	/**
	 * 工单垫款还款回调处理
	 * @param map
	 * @return
	 */
	public String backToGDAdvances(Map<String,Object> map){	
		Calendar now = Calendar.getInstance();
		/*******************垫款单更新********************/
		Map<String,Object>mapActual=new HashMap<String,Object>();
		mapActual.put("id", map.get("key"));
		List<Map<String,Object>> mapPList=gdMapper.getGdYetAdvancesAllById(mapActual);//查询出借款信息
		for(int j=0;j<mapPList.size();j++){
			now.add(Calendar.SECOND, 1);
			String actual_operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
			mapActual.put("actual_operation_date", actual_operation_date);
			mapActual.put("advances_type",StaticData.Proof_Yet_Advances_IN);
			mapActual.put("advances_id", mapPList.get(j).get("advances_id"));
			String voucher_id=String.valueOf(mapPList.get(j).get("voucher_id"));
			mapActual.put("voucher_id", voucher_id);
			BigDecimal zero = new BigDecimal(0);
			BigDecimal already_money = new BigDecimal(String.valueOf(mapPList.get(j).get("already_money")));//已还款金额
			BigDecimal yet_money = new BigDecimal(String.valueOf(mapPList.get(j).get("money")));//本次还款金额
			BigDecimal on_money = new BigDecimal(String.valueOf(mapPList.get(j).get("on_money")));//本次本金
			BigDecimal lxMoney = new BigDecimal(String.valueOf(mapPList.get(j).get("lxMoney")));
			if(on_money.add(lxMoney).subtract(yet_money).compareTo(zero)==0){
				mapActual.put("on_money", zero);
				mapActual.put("yet","1");
			}else{
				mapActual.put("on_money", on_money.add(lxMoney).subtract(yet_money));
				mapActual.put("yet","0");
			}
			mapActual.put("already_money",  yet_money.add(already_money));
			//更新本金
			gdMapper.updateAdvancesOnMoneyById(mapActual);
		}
		return null;
	}
	/**
	 * 项目支付回调处理
	 * 1>supplier_finance_out_detail finance_out减少
	 * 2>supplier_finance_out_log 增加记录
	 * @param map
	 * @return
	 */
	public String flowBackToXMPayDeal(Map<String,Object> map){	
		map.put("id", map.get("key"));
		List<Map<String,Object>> listPayDetail=xmFinanceMapper.viewXmPayDetail(map);
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		Map<String,Object> mapPay = xmFinanceMapper.viewXmPay(map);
		for(int i=0;i<listPayDetail.size();i++){
			Map<String, Object> m = listPayDetail.get(i);
			m.put("supplier_id", mapPay.get("pay_to_id"));
			xmFinanceMapper.updateSupplier(m);
			
			Map<String,Object> fod = xmFinanceMapper.getSupplierFOD(m);
			xmFinanceMapper.updateXMSupplierFinance(m);
			
			BigDecimal before_finance_out = new BigDecimal(String.valueOf(fod.get("finance_out")));
			BigDecimal pay_value = new BigDecimal(String.valueOf(m.get("now_pay")));
			Map<String,Object> fodLogMap = new HashMap<String,Object>();
			fodLogMap.put("detail_id", fod.get("id"));
			fodLogMap.put("before_finance_out", before_finance_out);
			fodLogMap.put("supplier_id", mapPay.get("pay_to_id"));
			fodLogMap.put("supplier", mapPay.get("pay_to_name"));
			fodLogMap.put("operation_date", operation_date);
			fodLogMap.put("proof_type", StaticData.XM_SUPPLIER_PROCESS_FINANCE_OUT);
			fodLogMap.put("proof_id", mapPay.get("id"));
			fodLogMap.put("finance_out", pay_value);
			fodLogMap.put("after_finance_out", before_finance_out.subtract(pay_value));
			fodLogMap.put("summary", "项目【"+mapPay.get("xm_code")+"】进度支付采购商，应付减少");
			crmMapper.addSupplierFODLog(fodLogMap);
		}
		BigDecimal pay_value = new BigDecimal(String.valueOf(mapPay.get("pay_value")));
		BigDecimal cut_payment = new BigDecimal(String.valueOf(mapPay.get("cut_payment")));
		List<Map<String,Object>> listLoan = xmFinanceMapper.listWorkerLoan(mapPay);
		List<Map<String,Object>> listNewLoan = new ArrayList<Map<String,Object>>();
		if(listLoan.size()>0&&null!=listLoan){
			//查询出此分包的未还借款单
				for(int i=0;i<listLoan.size();i++){
					Map<String,Object> mapLoan = listLoan.get(i);
					if(null!=mapLoan){
						BigDecimal loanMoney = new BigDecimal(String.valueOf(mapLoan.get("pay_money")));//剩余借款钱
						BigDecimal already_money = new BigDecimal(String.valueOf(mapLoan.get("already_money")));//借款金额+加本金
						BigDecimal yetMoney =cut_payment.add(already_money);
						Map<String,Object> lastLoan = xmFinanceMapper.getLastWorkerLoan(mapPay);
						//最后一笔借款单的id
						String lastId ="";
						if(null != lastLoan){
							lastId = String.valueOf(lastLoan.get("id"));
						}
						if(lastId.equals(String.valueOf(mapLoan.get("id")))){
							mapLoan.put("yet", "0");
							mapLoan.put("money",cut_payment.add(already_money) );
							listNewLoan.add(mapLoan);
							break;
						}else if(yetMoney.compareTo(loanMoney)==-1){
							mapLoan.put("yet", "0");
							mapLoan.put("money",yetMoney);
							listNewLoan.add(mapLoan);
							break;
						}else if(yetMoney.compareTo(loanMoney)==0){
							mapLoan.put("money",yetMoney);
							mapLoan.put("yet", "1");
							listNewLoan.add(mapLoan);
							break;
						}else{
							mapLoan.put("money",loanMoney);
							mapLoan.put("yet", "1");
							listNewLoan.add(mapLoan);
							cut_payment=yetMoney.subtract(loanMoney);
						}
						listNewLoan.add(mapLoan);
					}
				}
			}
			if(listNewLoan.size()>0){
				xmFinanceMapper.updateWorkLoan(listNewLoan);
			}
		//xm_base purchase_has_payable 字段数值增加，已付采购款增加。
		mapPay.put("purchase_has_payable", pay_value);
		xmFinanceMapper.addXMPurchaseHasPayable(mapPay);
		//项目辅助状态处理
		Map<String,Object> mstatus=new HashMap<String, Object>();
		mstatus.put("xm_id", mapPay.get("xm_id"));
		mstatus.put("xm_business_step", StaticData.XM_HAS_JDFK);
		xMAssistMapper.addXMBusinessStep(mstatus);
		return null;
	}
	/**
	 * 项目经济考评回调处理
	 * @param map
	 * @return
	 */
	public String backToGDUpdateEvaluation(Map<String,Object> map){	
		map.put("id", map.get("key"));
		map.put("fin_eval_id", map.get("key"));
		//1.查询出部门总利润，已经分摊利润
		//2.毛利分摊明细（部门所分摊金额）
		//3.更新部门账户表，以及部门账户日志
		Map<String,Object> mapEvaluation=xMMapper.getXmvaluationById(map);
		List<Map<String,Object>> listEvualDetail = xMMapper.listXmvaluationDetail(map);
		BigDecimal alreadt_profit = new BigDecimal(0);
		BigDecimal already_profit = new BigDecimal(String.valueOf(mapEvaluation.get("already_profit")));
		Calendar now = Calendar.getInstance();
		for(int i=0;i<listEvualDetail.size();i++){
			now.add(Calendar.SECOND, 1);
			String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
			Map<String, Object> m = listEvualDetail.get(i);
			//累加出已经分摊总利润
			 BigDecimal profit = new BigDecimal(String.valueOf(m.get("avg_profit")));
			 alreadt_profit=  new BigDecimal(profit.add(alreadt_profit).doubleValue());
			 //添加到部门账户
			 /*****************部门账户日志添加******************/
				Map<String,Object>mapD=financeMapper.getFinanceDeptByDeptId(String.valueOf(m.get("dept_id")));
				BigDecimal before_money = new BigDecimal(String.valueOf(mapD.get("money")));
				Map<String,Object>mapDept=new HashMap<String,Object>();
				mapDept.put("type", StaticData.FINANCE_IN);//类别支出
				mapDept.put("proof_type", StaticData.Proof_XM_EVAL);//凭证类型
				mapDept.put("finance_dept_id", mapD.get("id"));//部门id
				mapDept.put("proof_id",mapEvaluation.get("id"));//凭证id
				mapDept.put("before_money",before_money);//交易之前账户金额
				before_money=before_money.add(already_profit);
				mapDept.put("money",profit);//金额
				mapDept.put("summary","项目["+mapEvaluation.get("xm_code")+"]项目经济考评利润分摊");//摘要
				mapDept.put("person_id", mapEvaluation.get("creator_id"));//经办人id
				mapDept.put("person", mapEvaluation.get("creator"));//经办人
				mapDept.put("operation_date", operation_date);//操作时间
				financeMapper.addFinanceDeptLog(mapDept);
				
				if(String.valueOf(m.get("dept_id")).equals(String.valueOf(mapEvaluation.get("dept_id")))){
					//本部门账户分摊利润出去的金额日期
					Map<String,Object>mapMyDept=new HashMap<String,Object>();
					mapMyDept.put("type", StaticData.FINANCE_OUT);//类别支出
					mapMyDept.put("proof_type", StaticData.Proof_XM_EVAL);//凭证类型
					mapMyDept.put("finance_dept_id", mapD.get("id"));//部门id
					mapMyDept.put("proof_id",mapEvaluation.get("id"));//凭证id
					mapMyDept.put("before_money",before_money);//交易之前账户金额
					mapMyDept.put("money",already_profit);//金额
					mapMyDept.put("summary","项目["+mapEvaluation.get("xm_code")+"]项目经济考评利润分摊支出");//摘要
					mapMyDept.put("person_id", mapEvaluation.get("creator_id"));//经办人id
					mapMyDept.put("person", mapEvaluation.get("creator"));//经办人
					mapMyDept.put("operation_date", operation_date);//操作时间
					financeMapper.addFinanceDeptLog(mapMyDept);
					}
				//如果是本部门的话减去利润
				map.put("dept_id",m.get("dept_id"));
				map.put("finance_dept_id",mapD.get("id"));
				if(String.valueOf(m.get("dept_id")).equals(String.valueOf(mapEvaluation.get("dept_id")))){
					map.put("money", already_profit.subtract(profit));
					financeMapper.subFinanceDeptMoney(map);
				}else{
					map.put("money", profit);
					financeMapper.addFinanceDeptMoneyByDept(map);
				}
		}
		mapEvaluation.put("alreadt_profit", alreadt_profit);
		xMMapper.updateEvaluationById(mapEvaluation);
		return null;
	}
	/**
	 * 项目支付施工队回调处理
	 * 1>项目支付款 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMPayWorkerDeal(Map<String,Object> map){	
			map.put("id", map.get("key"));
			Map<String,Object> mapPay = xmFinanceMapper.viewXmPay(map);
			BigDecimal d2 = new BigDecimal(String.valueOf(mapPay.get("pay_value")));	
			BigDecimal cut_payment = new BigDecimal(String.valueOf(mapPay.get("cut_payment")));	
			//xm_base work_has_payable 字段数值增加。
			mapPay.put("work_has_payable", d2);
			xmFinanceMapper.addXMWorkerHasPayable(mapPay);
			
			String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
			Calendar now = Calendar.getInstance();
			BigDecimal zero = new BigDecimal(0);
			List<Map<String,Object>> listPayDetail=xmFinanceMapper.viewXmPayWorkerDetail(map);
			if(listPayDetail!=null&& listPayDetail.size() > 0){
				for(int i=0;i<listPayDetail.size();i++){
					Map<String, Object> m = listPayDetail.get(i);
					String worker_id = String.valueOf(mapPay.get("pay_to_id"));
					m.put("worker_id", worker_id);
					BigDecimal finance_out = new BigDecimal(String.valueOf(m.get("now_pay")));
					if(finance_out.compareTo(zero)>0){
						m.put("finance_out", zero.subtract(finance_out));
						crmMapper.updateWorkerFO(m);
						BigDecimal before_finance_out = new BigDecimal(0);
						Map<String,Object> fod = crmMapper.getWorkerFOD(m);
						String detail_id = null;
						if(fod==null){
							//如果分包应付明细没有值那么新增一条记录
							Map<String, Object> m2=new HashMap<String, Object>();
							detail_id = UUID.randomUUID().toString();
							m2.put("id", detail_id);
							m2.put("gd_id", m.get("gd_id"));
							m2.put("worker_id", worker_id);
							m2.put("already_pay", finance_out);
							m2.put("finance_out", zero.subtract(finance_out));
							xmFinanceMapper.addXMWorkerFinance(m2);	
						}else{
							 before_finance_out = new BigDecimal(String.valueOf(fod.get("finance_out")));
							 detail_id = String.valueOf(fod.get("id"));
							xmFinanceMapper.updateXMWorkerFinance(m);
						}
						//产生日志
						Map<String,Object> fodLogMap = new HashMap<String,Object>();
						fodLogMap.put("detail_id", detail_id);
						fodLogMap.put("before_finance_out", before_finance_out);
						fodLogMap.put("worker_id", worker_id);
						fodLogMap.put("worker", mapPay.get("pay_to_name"));
						fodLogMap.put("operation_date", operation_date);
						fodLogMap.put("proof_type", StaticData.XM_WORKER_PROCESS_FINANCE_OUT);
						fodLogMap.put("proof_id", mapPay.get("id"));
						fodLogMap.put("finance_out", finance_out);
						fodLogMap.put("after_finance_out", before_finance_out.subtract(finance_out));
						fodLogMap.put("summary", "项目【"+mapPay.get("xm_code")+"】进度支付分包商，应付减少");
						crmMapper.addWorkerFODLog(fodLogMap);
					}
				}
			}
			if(cut_payment.compareTo(zero)>0){
				//更新班组垫款本金，与已经还款金额
				Map<String,Object> advMap = new HashMap<String,Object>();
				advMap.put("id", mapPay.get("id"));
				advMap.put("xm_id", mapPay.get("xm_id"));
				advMap.put("worker_id",mapPay.get("pay_to_id"));
				List<Map<String,Object>> listAdv =gdMapper.listGdYetAdvancesByYetId(advMap);
				if(listAdv != null && listAdv.size()>0){
					for(int j=0;j<listAdv.size();j++){
						String actual_operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
						Map<String,Object> mAdv =listAdv.get(j);
						BigDecimal already_money = new BigDecimal(String.valueOf(mAdv.get("already_money")));//已还款金额
						BigDecimal yet_money = new BigDecimal(String.valueOf(mAdv.get("yet_money")));//本次还款金额
						BigDecimal now_on_money = new BigDecimal(String.valueOf(mAdv.get("now_on_money")));//当前本金
						BigDecimal lxMoney = new BigDecimal(String.valueOf(mAdv.get("lxMoney")));
						if(now_on_money.add(lxMoney).subtract(yet_money).compareTo(zero)==0){
							advMap.put("on_money", zero);
							advMap.put("yet","1");
						}else{
							advMap.put("on_money", now_on_money.add(lxMoney).subtract(yet_money));
							advMap.put("yet","0");
						}
							advMap.put("advances_id",mAdv.get("id"));
							advMap.put("actual_operation_date",actual_operation_date);
							advMap.put("already_money",  yet_money.add(already_money));
							//更新本金
							if(yet_money.compareTo(zero)>0){
								gdMapper.updateAdvancesOnMoneyById(advMap);
							}
						}
					}
			}
			List<Map<String,Object>> listLoan = xmFinanceMapper.listWorkerLoan(mapPay);
			List<Map<String,Object>> listNewLoan = new ArrayList<Map<String,Object>>();
			if(listLoan.size()>0&&null!=listLoan){
					//查询出此分包的未还借款单
					for(int i=0;i<listLoan.size();i++){
						Map<String,Object> mapLoan = listLoan.get(i);
						if(null!=mapLoan){
							BigDecimal loanMoney = new BigDecimal(String.valueOf(mapLoan.get("pay_money")));//剩余借款钱
							BigDecimal already_money = new BigDecimal(String.valueOf(mapLoan.get("already_money")));//借款金额+加本金
							BigDecimal yetMoney =cut_payment.add(already_money);
							//最后一笔借款单的id
							String lastId ="";
							if(yetMoney.compareTo(loanMoney)==-1){
								mapLoan.put("yet", "0");
								mapLoan.put("money",yetMoney);
								listNewLoan.add(mapLoan);
								break;
							}else if(yetMoney.compareTo(loanMoney)==0){
								mapLoan.put("money",yetMoney);
								mapLoan.put("yet", "1");
								listNewLoan.add(mapLoan);
								break;
							}else{
								mapLoan.put("money",loanMoney);
								mapLoan.put("yet", "1");
								listNewLoan.add(mapLoan);
								cut_payment=yetMoney.subtract(loanMoney);
							}
							listNewLoan.add(mapLoan);
						}
					}
				}
				if(listNewLoan.size()>0){
					xmFinanceMapper.updateWorkLoan(listNewLoan);
				}
			Map<String,Object> mstatus=new HashMap<String, Object>();
			mstatus.put("xm_id", mapPay.get("xm_id"));
			mstatus.put("xm_business_step", StaticData.XM_HAS_JDFK);
			xMAssistMapper.addXMBusinessStep(mstatus);
		return null;
	}
	
	/**
	 * 项目结算支付回调处理-施工队
	 * 1>项目支付款 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMEndWorkerPayDeal(Map<String,Object> map){	
			BigDecimal zero = new BigDecimal(0);
			map.put("id", map.get("key"));
			Map<String,Object> mapPay = xmFinanceMapper.viewXmPay(map);
			BigDecimal cut_payment = new BigDecimal(String.valueOf(mapPay.get("cut_payment")));	
			BigDecimal d2 = new BigDecimal(String.valueOf(mapPay.get("pay_value")));	
			//xm_base work_has_payable 字段数值增加，已付采购款增加。
			mapPay.put("work_has_payable", d2);
			xmFinanceMapper.addXMWorkerHasPayable(mapPay);
			String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
			Calendar now = Calendar.getInstance();
			List<Map<String,Object>> listPayDetail=xmFinanceMapper.viewXmPayWorkerDetail(map);
			if(listPayDetail!=null&& listPayDetail.size() > 0){
				for(int i=0;i<listPayDetail.size();i++){
					Map<String, Object> m = listPayDetail.get(i);
					String worker_id = String.valueOf(mapPay.get("pay_to_id"));
					m.put("worker_id", worker_id);
					BigDecimal finance_out = new BigDecimal(String.valueOf(m.get("now_pay")));
					//if(finance_out.compareTo(zero)>0){
						m.put("finance_out", zero.subtract(finance_out));
						crmMapper.updateWorkerFO(m);
						BigDecimal before_finance_out = new BigDecimal(0);
						Map<String,Object> fod = crmMapper.getWorkerFOD(m);
						String detail_id = null;
						if(fod==null){
							//如果分包应付明细没有值那么新增一条记录
							Map<String, Object> m2=new HashMap<String, Object>();
							detail_id = UUID.randomUUID().toString();
							m2.put("id", detail_id);
							m2.put("gd_id", m.get("gd_id"));
							m2.put("worker_id", worker_id);
							m2.put("already_pay", finance_out);
							m2.put("finance_out", zero.subtract(finance_out));
							xmFinanceMapper.addXMWorkerFinance(m2);	
						}else{
							 before_finance_out = new BigDecimal(String.valueOf(fod.get("finance_out")));
							 detail_id = String.valueOf(fod.get("id"));
							xmFinanceMapper.updateXMWorkerFinance(m);
						}
						//产生日志
						Map<String,Object> fodLogMap = new HashMap<String,Object>();
						fodLogMap.put("detail_id", detail_id);
						fodLogMap.put("before_finance_out", before_finance_out);
						fodLogMap.put("worker_id", worker_id);
						fodLogMap.put("worker", mapPay.get("pay_to_name"));
						fodLogMap.put("operation_date", operation_date);
						fodLogMap.put("proof_type", StaticData.XM_WORKER_END_FINANCE_OUT);
						fodLogMap.put("proof_id", mapPay.get("id"));
						fodLogMap.put("finance_out", finance_out);
						fodLogMap.put("after_finance_out", before_finance_out.subtract(finance_out));
						fodLogMap.put("summary", "项目【"+mapPay.get("xm_code")+"】结算支付分包商，应付减少");
						crmMapper.addWorkerFODLog(fodLogMap);
				//	}
				}
			}
			if(cut_payment.compareTo(zero)>0){
				//更新班组垫款本金，与已经还款金额
				Map<String,Object> advMap = new HashMap<String,Object>();
				advMap.put("id", mapPay.get("id"));
				advMap.put("xm_id", mapPay.get("xm_id"));
				advMap.put("worker_id",mapPay.get("pay_to_id"));
				List<Map<String,Object>> listAdv =gdMapper.listGdYetAdvancesByYetId(advMap);
				if(listAdv != null && listAdv.size()>0){
					for(int j=0;j<listAdv.size();j++){
						String actual_operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(now.getTime());
						Map<String,Object> mAdv =listAdv.get(j);
						BigDecimal already_money = new BigDecimal(String.valueOf(mAdv.get("already_money")));//已还款金额
						BigDecimal yet_money = new BigDecimal(String.valueOf(mAdv.get("yet_money")));//本次还款金额
						BigDecimal now_on_money = new BigDecimal(String.valueOf(mAdv.get("now_on_money")));//当前本金
						BigDecimal lxMoney = new BigDecimal(String.valueOf(mAdv.get("lxMoney")));
						if(now_on_money.add(lxMoney).subtract(yet_money).compareTo(zero)==0){
							advMap.put("on_money", zero);
							advMap.put("yet","1");
						}else{
							advMap.put("on_money", now_on_money.add(lxMoney).subtract(yet_money));
							advMap.put("yet","0");
						}
							advMap.put("advances_id",mAdv.get("id"));
							advMap.put("actual_operation_date",actual_operation_date);
							advMap.put("already_money",  yet_money.add(already_money));
							//更新本金
							if(yet_money.compareTo(zero)>0){
								gdMapper.updateAdvancesOnMoneyById(advMap);
							}
						}
					}
			}
			List<Map<String,Object>> listLoan = xmFinanceMapper.listWorkerLoan(mapPay);
			List<Map<String,Object>> listNewLoan = new ArrayList<Map<String,Object>>();
			if(listLoan.size()>0&&null!=listLoan){
				//查询出此分包的未还借款单
				for(int i=0;i<listLoan.size();i++){
					Map<String,Object> mapLoan = listLoan.get(i);
					if(null!=mapLoan){
						BigDecimal loanMoney = new BigDecimal(String.valueOf(mapLoan.get("pay_money")));//剩余借款钱
						BigDecimal already_money = new BigDecimal(String.valueOf(mapLoan.get("already_money")));//借款金额+加本金
						BigDecimal yetMoney =cut_payment.add(already_money);
						//最后一笔借款单的id
						String lastId ="";
						if(yetMoney.compareTo(loanMoney)==-1){
							mapLoan.put("yet", "0");
							mapLoan.put("money",yetMoney);
							listNewLoan.add(mapLoan);
							break;
						}else if(yetMoney.compareTo(loanMoney)==0){
							mapLoan.put("money",yetMoney);
							mapLoan.put("yet", "1");
							listNewLoan.add(mapLoan);
							break;
						}else{
							mapLoan.put("money",loanMoney);
							mapLoan.put("yet", "1");
							listNewLoan.add(mapLoan);
							cut_payment=yetMoney.subtract(loanMoney);
						}
						listNewLoan.add(mapLoan);
					}
				}
			}
			if(listNewLoan.size()>0){
				xmFinanceMapper.updateWorkLoan(listNewLoan);
			}
			//项目辅助状态处理
			Map<String,Object> mstatus=new HashMap<String, Object>();
			mstatus.put("xm_id", mapPay.get("xm_id"));
			int c=xmFinanceMapper.hasEndWorkerPay(mstatus);
			if("1".equals(String.valueOf(mapPay.get("no_material")))&&c==1){
				mstatus.put("xm_business_step", StaticData.XM_HAS_JSFBEND);
				xMAssistMapper.addXMBusinessStep(mstatus);	
			}else{
			if(c==1){
				mstatus.put("xm_business_step", StaticData.XM_HAS_JSFBEND);
				xMAssistMapper.addXMBusinessStep(mstatus);	
			}
			}
		return null;
	}
	
	
	/**
	 * 项目结算支付回调处理-采购
	 * 1>项目支付款 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMEndSupplyPayDeal(Map<String,Object> map){	
		map.put("id", map.get("key"));
		List<Map<String,Object>> listPayDetail=xmFinanceMapper.viewXmPayDetail(map);
		String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		Map<String,Object> mapPay = xmFinanceMapper.viewXmPay(map);
		for(int i=0;i<listPayDetail.size();i++){
			Map<String, Object> m = listPayDetail.get(i);
			m.put("supplier_id", mapPay.get("pay_to_id"));
			xmFinanceMapper.updateSupplier(m);
			
			Map<String,Object> fod = xmFinanceMapper.getSupplierFOD(m);
			xmFinanceMapper.updateXMSupplierFinance(m);
			
			BigDecimal before_finance_out = new BigDecimal(String.valueOf(fod.get("finance_out")));
			BigDecimal pay_value = new BigDecimal(String.valueOf(m.get("now_pay")));
			Map<String,Object> fodLogMap = new HashMap<String,Object>();
			fodLogMap.put("detail_id", m.get("bus_id"));
			fodLogMap.put("before_finance_out", before_finance_out);
			fodLogMap.put("supplier_id", mapPay.get("pay_to_id"));
			fodLogMap.put("supplier", mapPay.get("pay_to_name"));
			fodLogMap.put("operation_date", operation_date);
			fodLogMap.put("proof_type", StaticData.XM_SUPPLIER_END_FINANCE_OUT);
			fodLogMap.put("proof_id", mapPay.get("id"));
			fodLogMap.put("finance_out", pay_value);
			fodLogMap.put("after_finance_out", before_finance_out.subtract(pay_value));
			fodLogMap.put("summary", "项目【"+mapPay.get("xm_code")+"】结算支付采购商，应付减少");
			crmMapper.addSupplierFODLog(fodLogMap);
		}
		BigDecimal pay_value = new BigDecimal(String.valueOf(mapPay.get("pay_value")));
		//xm_base purchase_has_payable 字段数值增加，已付采购款增加。
		mapPay.put("purchase_has_payable", pay_value);
		xmFinanceMapper.addXMPurchaseHasPayable(mapPay);
		
		//项目辅助状态处理
		Map<String,Object> mstatus=new HashMap<String, Object>();
		mstatus.put("xm_id", mapPay.get("xm_id"));
		int c=xmFinanceMapper.hasEndSupplyPay(mstatus);
		if(c==1){
			mstatus.put("xm_business_step", StaticData.XM_HAS_JSCGEND);
			xMAssistMapper.addXMBusinessStep(mstatus);	
		}
		return null;
	}
	
	/**
	 * 项目材料平衡回调处理
	 * 1>项目业务状态 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMMaterBalanceDeal(Map<String,Object> map){
		map.put("id", map.get("key"));
		//项目辅助状态处理
		Map<String,Object> m=new HashMap<String, Object>();
		m.put("xm_id", map.get("id"));
		m.put("xm_business_step", StaticData.XM_HAS_CLPH);
		xMAssistMapper.addXMBusinessStep(m);
		m.put("xm_progress_status", StaticData.SUBMISSION);
		xMAssistMapper.updateXMProgressStatus(m);
		return null;
	}
	/**
	 * 工单领料退料回调处理
	 * @param map
	 * @return
	 */
	public String backToGDReturn(Map<String,Object> map){
		map.put("return_id", map.get("key"));
		List<Map<String,Object>> retList= gdMapper.listGDReturnDetail(map);
		if(retList!=null&retList.size()>0){
			for(int i=0;i<retList.size();i++){
				Map<String,Object> m=retList.get(i);
				m.put("apply_id", m.get("business_id"));
				if("1".equals(String.valueOf(m.get("business_type")))){
					//甲供领料数量更新
					gdMapper.updateGdJgApplyMaterial(m);
					//更新预估材料的已经使用数量
					m.put("num", m.get("return_num"));
					gdMapper.updateAssumeSubMaterial(m);
				}else if("2".equals(String.valueOf(m.get("business_type")))){
					//乙供领料数量更新
					gdMapper.updateGdYgApplyMaterial(m);
					//更新预估材料的已经使用数量
					m.put("num", m.get("return_num"));
					gdMapper.updateAssumeSubMaterial(m);
				}else if("3".equals(String.valueOf(m.get("business_type")))){
					//领用厂家库数量更新
					gdMapper.updateSupplierApplyMaterial(m);//领用更新
					//将退还的材料如部门共余库，【部门，材料，数量】
					//该部门有无该材料，有则更新数量，无则插入一条记录
					Map<String,Object> selfDBMap = new HashMap<String,Object>();//工余库日志
					Map<String,Object> queryParam = new HashMap<String,Object>();
					queryParam.put("dept_id", m.get("dept_id"));
					queryParam.put("type", 2);//2：工余库
					queryParam.put("product_id", m.get("material_id"));
					Map<String,Object> mySelfMaterialMap= wareHouseMapper.getMySelfMaterial(queryParam);
					if(mySelfMaterialMap == null){
						//表示当前该部门没有该材料记录,则添加该记录
						List<Map<String,Object>> dbl = new ArrayList<Map<String,Object>>();
						Map<String,Object> dbMap = new HashMap<String,Object>();
						String warehouse_id = wareHouseMapper.getMySelfWarehouseByDeptId(String.valueOf(m.get("dept_id")));
						dbMap.put("warehouse_id", warehouse_id);
						dbMap.put("product_id", m.get("material_id"));
						dbMap.put("cost", 0);
						dbMap.put("num", m.get("return_num"));
						dbMap.put("top", 1000);
						dbMap.put("low", 0);
						dbl.add(dbMap);
						wareHouseMapper.addMyMaterialDB(dbl);//工余库增加
						//产生日志
						selfDBMap.put("warehouse_id", warehouse_id);
					}else{
						//库存增加，生成库存变更日志
						m.put("db_id", mySelfMaterialMap.get("db_id"));
						m.put("num", m.get("return_num"));
						wareHouseMapper.addDBNum(m);//工余库增加
						selfDBMap.put("warehouse_id", mySelfMaterialMap.get("warehouse_id"));
					}
					selfDBMap.put("customer_id", "");
					selfDBMap.put("project_id", "");
					selfDBMap.put("gd_id", "");
					selfDBMap.put("supplier_id", "");
					selfDBMap.put("product_id", m.get("material_id"));
					selfDBMap.put("num", m.get("return_num"));
					selfDBMap.put("cost", 0);
					selfDBMap.put("person_id", map.get("att_user_id"));
					selfDBMap.put("person", map.get("att_user_name"));
					String operation_date = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
					selfDBMap.put("operation_date", operation_date);
					selfDBMap.put("direction", StaticData.DB_IN);
					selfDBMap.put("business_type", StaticData.GD_SUPPLISER_GY);
					selfDBMap.put("business_id", "");
					selfDBMap.put("summary", "工单厂家余料入工余，库存增加");
					selfDBMap.put("id", UUID.randomUUID().toString());
					List<Map<String,Object>> selfDBList = new ArrayList<Map<String,Object>>();//工余库日志
					selfDBList.add(selfDBMap);
					wareHouseMapper.addDBLog1(selfDBList);
//					gdMapper.updateSupplierPurchaseMaterial(m);//补采购更新
				}
				
			}
		}
		return null;
	}
	
	/**
	 * 项目结算收入回调处理
	 * 1>项目业务状态 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMInmoneyBalanceDeal(Map<String,Object> map){
		String operation_time = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		map.put("id", map.get("key"));
		map.put("xm_id", map.get("key"));
		map.put("status", 3);
		//获取项目对应结算数据xm_end_inmoney数据
		Map<String,Object> xmEndInM=xMMapper.getEndInMoneyXMById(map);
		//获取项目开票数据listXMInvoiceByXMId
//	   List<Map<String, Object>> invs= xmFinanceMapper.listXMInvoiceByXMId(map);
	   List  <Map<String, Object>>endDetails= xmFinanceMapper.listXMEndInMoneyDetail(map);
	   boolean hasManageMoney=false;
		//将未结算票据进行结算插入表xm_in_money
	   BigDecimal in_money_total=new BigDecimal(0);
	   for(int i=0;i<endDetails.size();i++){
		   Map<String, Object> minv=endDetails.get(i);
//		  Double account_receivable=Double.parseDouble(minv.get("account_receivable").toString());
//		  Double has_receivable=Double.parseDouble(minv.get("has_receivable").toString());
		  //Double in_money=account_receivable-has_receivable;
		   BigDecimal  in_money =new BigDecimal(String.valueOf(minv.get("end_pay")));
		  if(in_money==null || in_money.doubleValue()==0){
			  
		  }
		  else{
			  Map<String,Object> m= new HashMap<String,Object>();
	    		m.put("id", UUID.randomUUID().toString());
	    		m.put("xm_id", minv.get("xm_id"));
	    		m.put("xm_code", xmEndInM.get("xm_code"));
	    		m.put("xm_name", xmEndInM.get("xm_name"));
	    		m.put("xm_invoice_id", minv.get("xm_invoice_id"));
	    		m.put("remark","项目【"+xmEndInM.get("xm_code")+"】结算收款");
	    		m.put("operation_time",operation_time);
	    		m.put("creator_id", xmEndInM.get("creator_id"));
	    		m.put("creator", xmEndInM.get("creator"));
	    		m.put("in_money",in_money);
	    		if(hasManageMoney){
	    			m.put("manage_money", 0);
	    		}else{
	    			m.put("manage_money",xmEndInM.get("manage_money"));	
	    		}
	    		m.put("status",3);
	    		m.put("in_type", StaticData.INMONEY_JS);;//结算类型：0进度款，1结算款
	    	   	xmFinanceMapper.addXMInMoney(m);
	    	  //更新开票已开票数据
	    	   	xmFinanceMapper.addXMInvoiceHashReceivable(m);
	    	   	in_money_total = in_money_total.add(in_money);
	    	   	
	    		 //该项目对应客户的应收减少
	    		Map<String,Object> queryMap = new HashMap<String,Object>();
	    		queryMap.put("customer_id", xmEndInM.get("customer_id"));
	    		queryMap.put("xm_id", xmEndInM.get("xm_id"));
	    		BigDecimal zero = new BigDecimal(0);
	    		zero = zero.subtract(in_money);
	    		queryMap.put("finance_in", zero);
	    		crmMapper.updateCustomerFI(queryMap);//客户应收总额减少
	    		
	    		Map<String,Object> cfid = crmMapper.getCustomerFID(queryMap);
	    		BigDecimal before_finance_in = new BigDecimal(String.valueOf(cfid.get("finance_in")));
	    		cfid.put("finance_in", zero);
	    		crmMapper.updateCustomerFID(cfid);//客户对应项目的应收减少
	    		
	    		//产生日志
	    		Map<String,Object> fidLogMap = new HashMap<String,Object>();
	    		fidLogMap.put("detail_id", cfid.get("id"));
	    		fidLogMap.put("before_finance_in", before_finance_in);
	    		fidLogMap.put("customer_id", xmEndInM.get("customer_id"));
	    		fidLogMap.put("customer", xmEndInM.get("customer"));
	    		fidLogMap.put("operation_date", new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date()));
	    		fidLogMap.put("proof_type", StaticData.XM_FINANCE_END_IN);
	    		fidLogMap.put("proof_id", m.get("xm_id"));
	    		fidLogMap.put("finance_in", in_money);
	    		fidLogMap.put("after_finance_in", before_finance_in.subtract(in_money));
	    		fidLogMap.put("summary", "项目【"+xmEndInM.get("xm_code")+"】收结算款【"+in_money+"】，应收减少");
	    		crmMapper.addCustomerFIDLog(fidLogMap);
		  }
	   }
		//将管理费用与结算收款费用更新到项目上xm_base
//	   <update id="addXMHasReceivable" parameterType="java.util.HashMap">
//		update xm_base set has_receivable=has_receivable+#{in_money} where id=#{xm_id}
//	</update>
//	<update id="addXMManagePrice" parameterType="java.util.HashMap">
//		update xm_base set xm_manage_price=xm_manage_price+#{xm_manage_price} where id=#{xm_id}
//	</update>
	   Map<String,Object> m2= new HashMap<String,Object>();
	   m2.put("in_money", in_money_total);
	   m2.put("xm_id", xmEndInM.get("xm_id"));
	   xMAssistMapper.addXMHasReceivable(m2);

	   m2.put("xm_manage_price", xmEndInM.get("manage_money"));
	   xMAssistMapper.addXMManagePrice(m2);	
		
		//项目辅助状态处理
		Map<String,Object> m=new HashMap<String, Object>();
		m.put("xm_id", map.get("xm_id"));
		m.put("xm_business_step", StaticData.XM_HAS_JSSR);
		xMAssistMapper.addXMBusinessStep(m);
		return null;
	}
	
	
	
	/**
	 * 项目质保金回收处理
	 * 1>项目业务状态 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMWarrantyDeal(Map<String,Object> map){
		String operation_time = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		map.put("id", map.get("key"));
		Map <String,Object> wmap = xmFinanceMapper.getWarrantyById(map);
		wmap.put("already_receive", wmap.get("warranty_value"));
		wmap.put("status", 2);
		xmFinanceMapper.updateWarranty(wmap);
		
		
		map.putAll(wmap);
		map.put("status", 3);
		//获取项目对应结算数据xm_end_inmoney数据
		Map<String,Object> xmEndInM=xMMapper.getEndInMoneyXMById(map);
		//获取项目开票数据listXMInvoiceByXMId
	   List<Map<String, Object>> invs= xmFinanceMapper.listXMInvoiceByXMId(map);
//	   List  <Map<String, Object>>endDetails= xmFinanceMapper.listXMEndInMoneyDetail(map);
	   boolean hasManageMoney=false;
		//将未结算票据进行结算插入表xm_in_money
	   BigDecimal in_money_total=new BigDecimal(0);
	   for(int i=0;i<invs.size();i++){
		   Map<String, Object> minv=invs.get(i);
		   BigDecimal account_receivable=new BigDecimal(String.valueOf(minv.get("account_receivable")));
		   BigDecimal has_receivable=new BigDecimal(String.valueOf(minv.get("has_receivable")));
		   BigDecimal in_money=account_receivable.subtract(has_receivable);
//		  Double  in_money =Double.parseDouble(minv.get("end_pay").toString());
		  if(in_money==null || in_money.doubleValue()==0){
			  
		  }
		  else{
			  Map<String,Object> m= new HashMap<String,Object>();
	    		m.put("id", UUID.randomUUID().toString());
	    		m.put("xm_id", minv.get("xm_id"));
	    		m.put("xm_code", xmEndInM.get("xm_code"));
	    		m.put("xm_name", xmEndInM.get("xm_name"));
	    		m.put("xm_invoice_id", minv.get("xm_invoice_id"));
	    		m.put("remark","项目【"+xmEndInM.get("xm_code")+"】质保金结算付款");
	    		m.put("operation_time",operation_time);
	    		m.put("creator_id", xmEndInM.get("creator_id"));
	    		m.put("creator", xmEndInM.get("creator"));
	    		m.put("in_money",in_money);
	    		if(hasManageMoney){
	    		m.put("manage_money", 0);
	    		}else{
	    			m.put("manage_money",xmEndInM.get("manage_money"));	
	    		}
	    		m.put("status",3);
	    		m.put("in_type", StaticData.INMONEY_ZB);;//结算类型：0进度款，1结算款
	    	   	xmFinanceMapper.addXMInMoney(m);
	    	  //更新开票已开票数据
	    	   	xmFinanceMapper.addXMInvoiceHashReceivable(m);
	    	   	in_money_total = in_money_total.add(in_money);
	    	   	
	    	    //该项目对应客户的应收减少
	    		Map<String,Object> queryMap = new HashMap<String,Object>();
	    		queryMap.put("customer_id", xmEndInM.get("customer_id"));
	    		queryMap.put("xm_id", xmEndInM.get("xm_id"));
	    		BigDecimal zero = new BigDecimal(0);
	    		zero = zero.subtract(in_money);
	    		queryMap.put("finance_in", zero);
	    		crmMapper.updateCustomerFI(queryMap);//客户应收总额减少
	    		
	    		Map<String,Object> cfid = crmMapper.getCustomerFID(queryMap);
	    		BigDecimal before_finance_in = new BigDecimal(String.valueOf(cfid.get("finance_in")));
	    		cfid.put("finance_in", zero);
	    		crmMapper.updateCustomerFID(cfid);//客户对应项目的应收减少
	    		
	    		//产生日志
	    		Map<String,Object> fidLogMap = new HashMap<String,Object>();
	    		fidLogMap.put("detail_id", cfid.get("id"));
	    		fidLogMap.put("before_finance_in", before_finance_in);
	    		fidLogMap.put("customer_id", xmEndInM.get("customer_id"));
	    		fidLogMap.put("customer", xmEndInM.get("customer"));
	    		fidLogMap.put("operation_date", new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date()));
	    		fidLogMap.put("proof_type", StaticData.XM_FINANCE_WARRANTY);
	    		fidLogMap.put("proof_id",xmEndInM.get("xm_id"));
	    		fidLogMap.put("finance_in", in_money);
	    		fidLogMap.put("after_finance_in", before_finance_in.subtract(in_money));
	    		fidLogMap.put("summary", "项目【"+xmEndInM.get("xm_code")+"】收质保金款【"+in_money+"】，应收减少");
	    		crmMapper.addCustomerFIDLog(fidLogMap);
	    	   	
		  }
	   }
		//将管理费用与结算收款费用更新到项目上xm_base
	   Map<String,Object> m2= new HashMap<String,Object>();
	   m2.put("in_money", in_money_total);
	   m2.put("xm_id", xmEndInM.get("xm_id"));
	   xMAssistMapper.addXMHasReceivable(m2);

	   m2.put("xm_manage_price", xmEndInM.get("manage_money"));
	   xMAssistMapper.addXMManagePrice(m2);	
		
		//项目辅助状态处理
		Map<String,Object> m=new HashMap<String, Object>();
		m.put("xm_id", map.get("xm_id"));
		m.put("xm_business_step", StaticData.XM_HAS_ZBJ);
		xMAssistMapper.addXMBusinessStep(m);
		return null;
	}
	
	/**
	  * 项目结算施工队与采购商回调处理
	 * 1>项目支付款 增加
	 * @param map
	 * @return
	 */
	public String flowBackToXMPayBalanceDeal(Map<String,Object> map){	
//		String operation_time = new SimpleDateFormat(StaticData.OPERATION_DATE_FORMATTER).format(new Date());
		map.put("id", map.get("key"));
		map.put("xm_id", map.get("key"));
//		Map<String,Object> xm = xMMapper.getXMById(map);
		BigDecimal fbPrice = new BigDecimal(0);
		BigDecimal fbCutPrice = new BigDecimal(0);
		BigDecimal fbEndPrice = new BigDecimal(0);
		BigDecimal cgFinanceOut = new BigDecimal(0);
		BigDecimal cgAreadyPay = new BigDecimal(0);
		BigDecimal cgEndPay = new BigDecimal(0);
		//获取支付信息
		  List<Map<String,Object>> cgList = xmFinanceMapper.listXmEndCgPayment(map);
		  for(int i=0;i<cgList.size();i++){
			  Map<String,Object> cg = cgList.get(i);
			  cgFinanceOut =cgFinanceOut.add(new BigDecimal(String.valueOf(cg.get("finance_out"))));
			  cgAreadyPay = cgAreadyPay.add(new BigDecimal(String.valueOf(cg.get("already_pay"))));
			  cgEndPay =  cgEndPay.add(new BigDecimal(String.valueOf(cg.get("end_pay"))));
	
			
		  }
//		  BigDecimal zero = new BigDecimal(0);
		  List<Map<String,Object>> fbList = xmFinanceMapper.listXmEndFbPayment(map);
		  for(int i=0;i<fbList.size();i++){
			  Map<String, Object> fb = fbList.get(i);
			  fbEndPrice = fbEndPrice.add(new BigDecimal(String.valueOf(fb.get("end_pay"))));
			  fbPrice = fbPrice.add(new BigDecimal(String.valueOf(fb.get("worker_pay"))));
			  fbCutPrice = fbCutPrice.add(new BigDecimal(String.valueOf(fb.get("cut_payment"))));
		  }
		 
//		  xmFinanceMapper. addXMGDSupplyPaymentDetail(xmPayDetailList);
//		 Collection c= xmPayMapList.values();
//		 Iterator it=c.iterator();
//		  while(it.hasNext()){
//			  
//			  Map <String, Object>xmPay=(Map<String, Object>)it.next();
//			  if(xmPay.get("pay_type").toString().equals("2")){
//				  xmPay.put("in_type", StaticData.PAY_JS);
//				  xmFinanceMapper.addXMGDSupplyPayment(xmPay);
////				Double d2=-Double.parseDouble(xmPay.get("pay_value").toString());
////				//xm_base purchase_has_payable 字段数值增加，已付采购款增加。
////				xmPay.put("purchase_has_payable", d2);
////				xmFinanceMapper.addXMPurchaseHasPayable(xmPay);
//			  }else if(xmPay.get("pay_type").toString().equals("1")){
//				  xmFinanceMapper.addXMGDSupplyPayment(xmPay);
////				    Double d2=-Double.parseDouble(xmPay.get("pay_value").toString());
////				  //xm_base purchase_has_payable 字段数值增加，已付施工款增加。
////					xmPay.put("purchase_has_payable", d2);
////					xmFinanceMapper.addXMWorkerHasPayable(xmPay);	
//			  }
//			  
//		  }
		//项目辅助状态处理
			Map<String,Object> mstatus=new HashMap<String, Object>();
			mstatus.put("xm_id", map.get("xm_id"));
			mstatus.put("xm_business_step", StaticData.XM_HAS_JSZF);
			xMAssistMapper.addXMBusinessStep(mstatus);
			mstatus.put("xm_progress_status", StaticData.SETTLE);
			xMAssistMapper.updateXMProgressStatus(mstatus);
			/*约定付完款自动关闭项目的话，上面的将会被下面状态覆盖*/
//			mstatus.put("xm_business_step", StaticData.XM_HAS_CLOSE);
//			xMAssistMapper.addXMBusinessStep(mstatus);
//			mstatus.put("xm_progress_status", StaticData.PROCESS_CLOSE);
//			xMAssistMapper.updateXMProgressStatus(mstatus);
			
		//项目辅助金额处理
			Map<String,Object> mPrice=new HashMap<String, Object>();	
			mPrice.put("work_end_pay", fbEndPrice);
			mPrice.put("work_account_payable", fbPrice);//直接覆盖
			mPrice.put("work_cut_pay", fbCutPrice);
//			mPrice.put("lend_has_receivable", fbBorrowPrice);
//			mPrice.put("lend_interest_has_receivable", fbInterest);
			mPrice.put("purchase_account_payable", cgFinanceOut);
//			mPrice.put("purchase_has_payable", (cgAreadyPay.add(cgEndPay)));
			mPrice.put("xm_id",  map.get("xm_id"));
			xMAssistMapper.addXMEndPayPrice(mPrice);
		return null;
	}	
	
}
